I'm trying to work though the markdown previewer, not yet at the hard but but im already stuck. Why is the textarea not showing the updated text im typing?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState(state => {
input: event.target.value
})
}
render() {
return (
<body>
<div >
<form>
<textarea
id="editor"
placeholder="Type your code here..."
value={this.state.input} onChange={this.handleChange}
>{this.state.input}</textarea>
<div id="preview" >
<h1></h1>
<h2></h2>
<a></a>
<script></script>
</div>
</form>
</div>
</body>
);
}
}
ReactDOM.render(<App />, document.getElementById("target"));
I'm trying to work though the markdown previewer, not yet at the hard but but im already stuck. Why is the textarea not showing the updated text im typing?
CodePudding user response:
Update the handleChange
function like this:
handleChange(event) {
this.setState({
input: event.target.value
});
}
And set the value in the value attribute and remove it from inside the element like this:
<textarea
id="editor"
placeholder="..."
value={this.state.input} onChange={this.handleChange}>
</textarea>
CodePudding user response:
You are passing the state value wrong. It should be:
this.setState({
input: event.target.value
});
And as a side note, you are supposed to use className
instead of class
in React.js.
So the code looks like this:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ""
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
console.log(event.target.value);
this.setState({
input: event.target.value
});
}
render() {
return (
<body>
<div className="body-div">
<form>
<textarea
className="editor"
id="editor"
placeholder="Type your code here..."
value={this.state.input}
onChange={this.handleChange}
>
{this.state.input}
</textarea>
<div id="preview" className="preview">
<h1>{this.state.input}</h1>
<h2>{this.state.input}</h2>
<a>{this.state.input}</a>
<script></script>
</div>
</form>
</div>
</body>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Live demo here: https://codesandbox.io/s/setstate-class-l32m2u