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

pass an array from a child to parent ReactJS

i have an array in a component i want to export it or pass it to other component (parent)

child component :

export default function child(){

const arr = ["1020","52214","3325"]
return (
<div> child</div>
)
}

parent :

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

export default function parent(){

return (
<>
<div> parrent</div>
<child/>
</>
)
}

>Solution :

In react we don’t pass values from child to parent but the other way around: it’s a one-way data flow!

You can useState to create a stateful value and a set-function in the parent, pass the set function to the child and allow it to set the value.

Example:

export default function child(props){

const arr = ["1020","52214","3325"];
props.setMyArray(arr);

return (
<div> child</div>
)
} 

import { useState } from 'react';

export default function parent(){
  const [myArray, setArray] = useState([]);

  return (
    <>
    <div> parrent</div>
    <child setMyArray={setArray}/>
    </>
    )
  }
}
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