Skip to main content

Image on Click Component

credit

Thanks to Docux (Juniors017) for creating this component and sharing it with us.

The code for the component used for this functionality for should be placed in \src\components\ImageOnClick\index.*.

src\components\ImageOnClick\index.js
  // Import React and the useState hook, used to manage the visibility of the image.
import React, { useState } from 'react';
// Import clsx library for conditional classes.
import clsx from 'clsx';
// Importing the useBaseUrl function.
import useBaseUrl from '@docusaurus/useBaseUrl';
// Import styles from CSS module.
import styles from './styles.module.css';
// Define the ImageOnClick component as a function
// with imageUrl, altText, and buttonName as properties
export default function ImageOnClick({ imageUrl, altText, buttonName }) {
// State to track whether image should be shown or hidden.
const [showImg, setShowImg] = useState(false);
// Use the useBaseUrl function to generate the image URL.
const generatedImageUrl = useBaseUrl(imageUrl);

return (
// Using a <span> container since these links will often be inside <p>, so to avoid semantic errors on click, the span is ideal. Then creating a link with an event handler here on click (onClick). Then the 3 properties and their CSS classes defined in the site's custom CSS cursor is for modifying the cursor on hover.
<span>
<a onClick={() => setShowImg(!showImg)} className= {styles.cursor}>
{buttonName}
</a>
{showImg && (
<span className={styles.imageonclick}>
<img src={generatedImageUrl} alt={altText} />
</span>
)}
</span>
);
}

Creating a theme folder

To follow the Docusaurus documentation, we create a theme folder that will host the MDXcomponents file. This gives us src\theme\MDXComponents.*.

src\theme\MDXComponents.js
  import React from 'react';
// Importing the original mapper + our components according to the Docusaurus doc
import MDXComponents from '@theme-original/MDXComponents';
import ImageOnClick from '@site/src/components/ImageOnClick';

export default {
// Reusing the default mapping
...MDXComponents,
// Adding the ImageOnClick tag following the doc's process ;)
ImageOnClick,
};

Using the Component in an MDX File

Basic

<ImageOnClick imageUrl="/img/docux.png" altText="Dinosaur" buttonName="Click me" />
Click me

Emoji Button

<ImageOnClick imageUrl="/img/docux.png" altText="Dinosaur" buttonName="🔎" />

Using markdown emoji: 🔎

CSS

To center the image and apply the cursor pointer, we'll add some CSS

src\components\ImageOnClick\styles.module.css
  .imageonclick {
display: flex;
max-width: 50% !important;
margin: auto; /* Adjust this value according to your needs */
}
.cursor {
cursor: pointer;
}