As you are at that moment of learning the name of the component does not refer to the component and what it represents, but, you need to change the state of the input
text
, then you need to program that which is in the eventonChange
that input
, example:
handlerOnChangeInput = e => {
const {name, value} = e.target;
this.setState({[name]: value});
}
this function can change to the whole state of the input
, but, for this to work the name of input
has to be passed equal to the name of the created state variable which in its specific case is text
.
In general it is done so:
handlerOnChangeInput = e => {
this.setState({text: e.target.value});
}
but, is restricted only in this input
(can be done so also no problems, will only write a little more because the code will only work for that input
and if there are more that need to save state then have to write to each one, so I put the generic before, choose the best one for you)
The complete and functional example:
class Button2 extends React.Component {
constructor(props) {
super(props)
this.state = {
text: 'Your Name Here',
}
}
handlerSubmit = e => {
e.preventDefault();
console.log(this.state.text);
}
handlerOnChangeInput = e => {
const {name, value} = e.target;
this.setState({[name]: value});
}
render() {
return (
<form onSubmit={this.handlerSubmit}>
{this.state.text}
<input type="text" value={this.state.text} name="text" id="text" onChange={this.handlerOnChangeInput} />
<button onClick={this.clicked}>Click on me</button>
</form>
)
}
}
ReactDOM.render(<Button2/> , document.getElementById('root'));
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">Aguarde ...</div>
Observing: the button
in this case redeems the value of the state of the component in the created key, that is, it is different, in the case to take the value of the text
need to type this.state.text
.
Hello, could you explain these two lines of code? const {name, value} = e.target; this.setState({[name]: value}); and I tbm was in doubt the pq vc put a value, a name and an id in the input but did not put anything in the button. If you can answer me I will be grateful ! Thank you.
– Pedro
const {name, value} = e.target;
It’s like you doconst name = e.target.name;
andconst value = e.target.value;
I want to deconstructe.target
read and the part value, a name and an id in the input but did not put anything in the button is because it has to be done so I putname
andid
but I just needed thename
for the generic function to work and the button is a form Ubmit so the value is rescued from the state when Ubmit the form. @Giovannimanganotti– novic
Okay, thanks for the help !
– Pedro
If the answer to your question @Giovannimanganotti accepted
– novic