How to create clickable image in react js?

Hi Friends πŸ‘‹,

Welcome To aHoisting!

To create clickable image in react js, you have to use onClick in <img> tag. It will create clickable image in react js.

Today, I am going to show you, how to create clickable image in react js.

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

import React from 'react';
import ClickableImage from './ClickableImage';
import logo from './beautiful-nature.jpeg'

Step 3: Create a Component.

You can use onClick={handleClick} to create clickable image in react js.

<ClickableImage
  src={logo}
  alt="Clickable example"
  onClick={handleClick}
/>

Create clickable image example.

The below code is an example of a React. You have to import './ClickableImage' and use onClick in <img> tag to create clickable image in react js.

App.js

import React from 'react';
import ClickableImage from './ClickableImage';
import logo from './beautiful-nature.jpeg'

const App = () => {
  const handleClick = () => {
    alert('Image clicked!');
  };

  return (
    <ClickableImage
      src={logo}
      alt="Clickable example"
      onClick={handleClick}
    />
  );
};

export default App;

ClickableImage

import React from 'react';

const ClickableImage = ({ src, alt, onClick }) => {
  return (
    <img
    width={400}
    height={400}
    src={src}
    alt={alt}
    onClick={onClick}
    style={{ cursor: 'pointer' }} // Ensures the pointer cursor is shown
    />
  );
};

export default ClickableImage;

In the above code example, I have used the onClick in <img> tag to create clickable image in react js.

Check the output of the above code.

React, create, clickable, image

All the best πŸ‘