Passing Props from Child to Parent in React

Muwonge Nicholus
2 min readJan 1, 2021

Props are a very important aspect of React or React Native as they determine the characteristics of a Component. These need to be present for the Component to work as expected.For instance

<Input value={add_something} />

  • The prop value must be present for the Input field to work as expected.

You can read more about the props over at the react docs https://reactjs.org/docs/components-and-props.html.

Since components work in a network, they always share properties with each other for instance, a button inside a form may take on the backgroundColor similar to that of the parent or padding so it becomes crucial to know how to work past these properties between components.

There are a couple of methods in which components could access each other’s properties(props) like central state management libraries like Redux, then React’s Context API which I will get into in future posts and passing them on a component to component basis. Any other way, I will be happy to learn from you.

My focus will be on a component level where a child passes props to its parent component as it gave me hard time when I tried to implement it.

The example I will use below demonstrates just picking the button text and displaying it in the parent component.

// This is the parent component somewhere in my file structure or same file.It just takes child prop button text and displays it.export default function Parent() {    const [data_from_child, setData]= useState('');// this function should be taking in a value that will be passed in the child element    const passedProps=(value)=>{      setData(value)     }    return (       <div className="App">         <h1>Below is the button's text</h1>         <h3>{data_from_child}</h3>         <ChildComponent passProps={passedProps}/>       </div>      );}

The child component sets the value to be passed to the parent component

const ChildComponent=(props)=>{   const showButtonText=()=>{
// not the most ideal Id to use but it should do the job for this explanation.
return document.getElementById('test-button').innerHTML; } return( <button id='test-button'
// showButtonText returns a value that I pass in to the function in the parent component.
onClick={()=>props.passProps(showButtonText)}>
Button Name
</button>
)}

This implementation is for hooks and I am happy to see how you would approach it in the comments.

Find my actual working code here for testing.

Code for testing this out.

Thanks for reading. Cheers.

--

--

Muwonge Nicholus

I am a Javascript and Ruby engineer. I love designing user interfaces and currently working in payment systems.