12 February 2020

Reusable Image Button component example in react js

  • Create Components folder under src folder
  • Create  common folder under Components folder
  • Create ImageButton folder under common folder
  • Add index.js file under ImageButton folder and add below Code
import React from "react";
import "./style.css";

const ImageButton = ({ idsourcealtTextclassNameclickHandler }) => {
  return (
    <>
      <span onClick={clickHandler} role="button">
        <img id={id} src={source} alt={altText} className={className} />
      </span>
    </>
  );
};
export default ImageButton;
  • Add style.css file and add below Code
.img {
  border1px solid #ddd;
  border-radius4px;
  padding5px;
  width150px;
}
  • Go to Components Folder and Add ImageButtonEXP.js file and add below Code
import React from "react";
import ImageButton from "./common/ImageButton/index";

export default function ImageButtonEXP() {
  const clickHandler = e => {
    alert("Clicked on Image Button");
  };
  return (
    <>
      <ImageButton
        id={"img1"}
        altText={"my inage"}
        className={"img"}
        clickHandler={clickHandler}
        source={"http://allinoneweb.net/Including/Images/home/logo.png"}
      />
    </>
  );
}
  • Open App.js file and update code as below
import React from 'react';
import ImageButtonEXP from './Components/ImageButtonEXP'

function App() {
  return (
    <div>
      <ImageButtonEXP/>
    </div>
  );
}

export default App;

Output:



No comments:

Post a Comment