StochasticNerd StochasticNerd - 26 days ago 18
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);
}
handleSubmit(){
//Logic to get the data from the child and post to localhost:8080/
}
render(){
return(

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

);
}

}


This is my child component,

class Sidebar extends React.Component {

handleSubmitButton(event) {
event.preventDefault();

}

render() {
return (
<div>

<input type="text"/>

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


</div>
);

}
}

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

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: https://facebook.github.io/react/docs/refs-and-the-dom.html

Parent component:

handleSubmit() {
  console.log(this.textInput.value);
}

<Sidebar 
  inputRef={(input) => this.textInput = input} 
  handleSubmitButton={this.state.handleSubmit}
/>

Child component:

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