Beginnerprogrammer Beginnerprogrammer - 1 month ago 26
React JSX Question

ReactJs Print value instantly

I am new to reactjs and trying to print update value of input field. What I firstly tried was this:

var App = React.createClass({
render() {
return <div>
<h1>Hello, {this.props.name}</h1>
<input type="text" onKeyUp={this.handleChange} />
<p>{this.handleChange}</p>
</div>;
},
handleChange: function(event) {
return event.target.value;
}
});
App = React.createFactory(App);

React.render(
<App name="World" />,
document.getElementById('mount-point'));


But I don't get it why it is not working. Than I tried this: CodePen maybe someone can help me with printing instantly the value of the input field in the
<p>
element

Answer
var App = React.createClass({
    getInitialState: function() {
        return {
            text: "",
        };
    },
    handleChange: function(event) {
        this.setState({ text: event.target.value });
    },
    render() {
        return <div>
            <h1>Hello, {this.props.name}</h1>
            <input type="text" onChange={this.handleChange} />
            <p>{this.state.text}</p>
        </div>;
    },
});

You must store all state of the component in this.state. Use this.setState to update the state. When you update the state, the component is automatically rerendered with the new state.

The content of the paragraph is the current value of the state. onChange is commonly used instead of onKeyUp to handle changes of state in text inputs. handleChange will update the state when the text input changes.

Comments