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

React js Pass data from parent to child

I dont know why I cant pass the value that i set on may parent component to child component, ofcourse there is nothing wrong with getting or fetching the record, is there any wrong with my code?

import ChildComponent from "../components/Forms/ChildComponent";

const [showchild, setchild] = useState(false);
const [getData, setData] = useState(false);
useEffect(() => {
   ...
   setchild(true)
   setData(data) //the data is from my database and it has a record
   ...
})

return(

    {showchild ? (
      <>
        <ChildComponent getData={getData}></ChildComponent>
      </>
    )}
)

ChildComponent.js

export default function ChildComponent(getData) {

  useEffect(() => {
    console.log("get Data from Parent component: ", getData) // I dont know why I cant pass the value that i set on may parent component to 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

>Solution :

In your ChildComponent function, the getData parameter is actually the entire props object passed to the component. In order to access the getData property of the props object, you can destructure it like this:

export default function ChildComponent({ getData }) {
  useEffect(() => {
    console.log("get Data from Parent component: ", getData);
  });
}

Alternatively, you can access the getData property directly on the props object like this:

export default function ChildComponent(props) {
  useEffect(() => {
    console.log("get Data from Parent component: ", props.getData);
  });
}

It’s generally considered best practice to destructure the props object, however, because it makes the code easier to read and understand.

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