ReactJS - Forwarding input value to parent component
Ad
I have problem with rather simple task. On button click I want to console log inputs value. What happens is that it logs on input change and not on click. What am I doing wrong?
var Tasker = React.createClass({
getInitialState: function() {
return {
};
},
handleChange: function(event) {
this.setState({
value: event.target.value
});
},
render: function () {
return (
<div>
<input type="text" value={this.state.value} onChange={this.handleChange}/>
<button onClick={this.props.onClick(this.state.value)}>Add task</button>
</div>
);
}
});
var List = React.createClass({
handleNewTaskClick: function (value) {
console.log(value);
},
render: function () {
return (
<Tasker onClick={this.handleNewTaskClick}/>
);
}
});
ReactDOM.render(<List />, document.getElementById('react-app'));
JSbin link:https://jsbin.com/vororomuzo/edit?html,console,output
Ad
Answer
Ad
Not sure why the onClick is fired every time the state is changed as opposed to when the event is fired, but if you create a handleClick method and call it instead of handling it in the jsx it works correctly.
handleClick: function() {
this.props.onClick(this.state.value);
},
render: function () {
return (
<div>
<input
type="text"
value={this.state.value}
onChange{this.handleChange}
/>
<button onClick={this.handleClick}>Add task</button>
</div>
);
}
Updated jsbin
Ad
source: stackoverflow.com
Related Questions
Ad
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad