Passing {props} from Child to Parent in React

Olesya Miller
2 min readFeb 22, 2021

Hello my fellow React developers! Today I’m excited to write a post on how to pass props up, or from child to parent in the component tree.

We are used to passing props from parent to child. But have you ever wondered if it is possible to send props in the opposite direction?! The answer is yes, and now I’m going to demonstrate how to do that.

As an example I’m going to use my Search GitHub Users project.

We want to have everything centralized in our App.js. Let’s create a function searchUsers with a query parameter in the App component. In searchUsers we are going to make a call to the GitHub API. From the API documentation we know that we have to make the call to “https://api.github.com/users?q=${query}&client_id=${ your client id }&client_secret=${ your secret }” and pass it our parameters

//App.js ...class App extends Component {  state = { users: [] }  searchUsers = async query => {
const response = await axios.get(
'https://api.github.com/users?q=${query}&client_id=${ your client id }&client_secret=${ your secret }'
)
this.setState({ users: response.data.items })
}
...}

If you remember from my last week post, it is considered best practice to have each component responsible for just one thing. We are going to have a component responsible just for filtering. We are going to call it Search. In Search component we are going to have just one piece of state — query.

//Search.jsclass Search extends Component {  state = {query: ""}

}

In our Search component we will need to have a function that will be responsible for searching data based on form input. As we know, forms are controlled in React, so the input will be saved in the state and passed to our function as an argument. Let’s call our function onSubmit. But where are we going to get the content for our function? From the props! We are going to mount our Search component in the App component and pass it as a prop our searchUsers function that fetches data from the API

//App.js ...render(){
return(
<div>
<Search searchUsers={this.searchUsers} />
<Users users={this.props.users} />
</div>
)
}
...

And finally, we are going to invoke searchUsers in the Search component and pass it our state!

class Search extends Component {  state = {query: ""}  onSubmit = (e) => {
e.preventDefault()
this.props.searchUsers(this.state.query)
}
}

And this is it! Let’s quickly recap what we just did. We created a function in our App component with a parameter query and passed it as a prop to our Search component where we invoked the function and passed it our state as an argument. This is how you pass props from child to parent in React!

I hope you found this useful and happy coding! See you next week!

--

--