Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change attribute of a child component from parent in React?

I’m having a Child Component with img & h5 elements.I want to change the image and heading content in each component without rewriting the whole code of it.

Parent Component

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Child from "./services";


const Navbar = () => {

  return (
    <div className="d-flex flex-row justify-content-center">
      
     <Child/>
     <Child/>
     <Child/>
     <Child/>

    </div>
  );
};

export default Navbar;

Child component:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";

const Child = (props) => {
  return (
    <>
      <div className="ser-wrapper">
        <img src="https://api.time.com/wp-content/uploads/2019/08/better-smartphone-photos.jpg" id="myImage"/>
        <h5>Heading 1</h5>
      </div>
    </>
  )
};

export default Child;

enter image description here

I tried sending images SRC as props but didn’t work the way I wanted. I want to get different images and different heading content for each component.

>Solution :

Parent component

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import Child from "./services";
const Navbar = () => {
  return (
    <div className="d-flex flex-row justify-content-center">
  
     <Child heading="Heading 1" imgSrc="https://api.time.com/wp-content/uploads/2019/08/better-smartphone-photos.jpg" />
     <Child heading="Heading 2" imgSrc="https://media.istockphoto.com/photos/coahuilan-box-turtle-picture-id93385233?k=20&m=93385233&s=612x612&w=0&h=7pdWzLGa-XzIdvPvUsXzF91RomisLiGPiDnlr3iP00A=" />
    // ...etc

    </div>
  );
};
export default Navbar;

Child component

import React from "react";
import "bootstrap/dist/css/bootstrap.min.css";

const Child = (props) => {
  return (
    <>
      <div className="ser-wrapper">
        <img src={props.imgSrc} id="myImage"/>
        <h5>{props.heading}</h5>
      </div>
    </>
  )
};

export default Child;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading