StochasticNerd StochasticNerd - 10 months ago 82
Javascript Question

Passing data to parent in React

I'm new to React and thus the question.
I have a parent Component - HomePage with a child Component - SideBar.

My child component sidebar needs to pass a data back to the parent on a submit button click which the parent needs to post on an api.

This my parent component,

class HomePage extends React.Component{

constructor(props) {
this.handleSubmit = this.handleSubmit.bind(this);
//Logic to get the data from the child and post to localhost:8080/

<div className="col-md-2 left-pane">
<Sidebar handleSubmitButton={this.state.handleSubmit}/>



This is my child component,

class Sidebar extends React.Component {

handleSubmitButton(event) {


render() {
return (

<input type="text"/>

<button type="button" className="btn btn-info btn-icons" onClick={this.props.handleSubmitButton} >
<span className="glyphicon glyphicon-send" aria-hidden="true"/>



Sidebar.propTypes = {
handleSubmitButton: React.PropTypes.func

My question is how do I grab the input text with the onclick method on the sidebar button click and pass it up to the parent to post it on an api. Any help appreciated.

Answer Source

In your child component you can create a property for the ref attribute. Accessing DOM elements directly is usually done by setting refs.

in your parent component you can use an arrow function with a callback which allows you to access the DOM element anywhere within your parent component, by simply typing this.textInput

More information about refs can be found in the official React documentation:

Parent component:

handleSubmit() {

  inputRef={(input) => this.textInput = input} 

Child component:

<input ref={this.props.inputRef} type="text"/>