user944513 user944513 - 6 months ago 77
Javascript Question

how to send value one component to another component in react js?

could you please tell me how to send input field value on second component on button click .I have one button and input field in first component.On button click I need to send input field value to second component

here is my code
http://codepen.io/naveennsit/pen/GZbpeV?editors=0010

var { Router, Route,browserHistory } = ReactRouter
class First extends React.Component{
sendValue(){
browserHistory.push('/second');
}
render(){
return (<div>
<input type='text' />
<button onClick={this.sendValue}>send</button>
</div>)
}
}

class Second extends React.Component{
render(){
return <div>second component</div>
}
}
class Main extends React.Component{
render(){
return (
<Router history={browserHistory}>
<Route path='/' component={First}></Route>
<Route path='/second' component={Second}></Route>
</Router>)
}
}
React.render( <Main />,document.getElementById('app'));
browserHistory.push('/')

Answer

The best solution would be to create some architecture that would allow you to have a separate state object, change it, and pass changes on to your components. See Flux, or Redux.

For a pinpointed solution, you could use url params:

class First extends React.Component{
  sendValue(){
    browserHistory.push('/second/' + this.refs.textField.value);
  }

  render(){
    return (
      <div>
        <input type='text' ref='textField' />
        <button onClick={() => {this.sendValue()}}>send</button>
      </div>)
  }
}

class Second extends React.Component { 
  render(){
    return <div>second component: {this.props.params.test}</div>
  }
}

class Main extends React.Component{
  render(){
    return (
     <Router history={browserHistory}>
          <Route path='/' component={First}></Route>  
          <Route path='/second/:test' component={Second}></Route>  
    </Router>)
   }
}