12 February 2020

Reusable Image component example in react js

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

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

const IMAGES = [
  "http://allinoneweb.net/Including/Images/home/logo.png",
  "http://allinoneweb.net/Including/Images/home/logo.png",
  "http://allinoneweb.net/Including/Images/home/logo.png",
  "http://allinoneweb.net/Including/Images/home/logo.png",
  "http://allinoneweb.net/Including/Images/home/logo.png"
];

const ImageEXP = () => (
  <>
    {IMAGES.map(image => (
      <Image source={image} key={image} className={"img"} />
    ))}

    <Image
      id={"img1"}
      altText={"my inage"}
      className={"img"}
      source={
        "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"
      }
    />
  </>
);

export default ImageEXP;
  • Open App.js file and update code as below
import React from 'react';
import ImageEXP from './Components/ImageEXP'

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

export default App;

Output:


No comments:

Post a Comment