this is my code:
const Agregar = ({inputPregunta, validatePregunta}) => {
return(
<div id="content">
<h2>¿Cual es tu pregunta?</h2>
<input id="valorPregunta" type="text" placeholder="Añade aqui tu pregunta..." onChange={(e) => inputPregunta(e)}/>
{validatePregunta && <button>Agregar</button>}
</div>
);
}
What i am trying to do is when the input has something entered the prop validatePregunta (default is false) comes to true and the button element shows, for that i tried to do a method in the App.js file like this:
actualizarPregunta = (e) => {
this.setState({inputPregunta: e.target.value})
if(this.state.inputPregunta.trim().length > 0){
this.setState({validatePregunta: true})
} else {
this.setState({validatePregunta: false})
}
}
But nothing shows, is there's something that i am doing wrong?
Edit: Here is the code of the rendering for the props:
renderRoute = () => {
switch(this.state.route) {
case 'menu':
return (
<div>
<Header />
<Agregar inputPregunta={this.actualizarPregunta} validate={this.state.validatePregunta}/>
<Publications />
</div>
)
default :
return (
<div>
<Header />
<Publications />
</div>
)
}
}
render() {
return (
<div>
{
this.renderRoute(this.state.route)
}
</div>
);
}
This is how you use the compoennt
<Agregar inputPregunta={this.actualizarPregunta} validate={this.state.validatePregunta}/>
you are passing the value of this.state.validatePregunta
by property name of validate
and then you are expecting something validatePregunta
in component Agregar
, but it should be actually validate
const Agregar = ({inputPregunta, validatePregunta}) => { //incorrect
const Agregar = ({inputPregunta, validate}) => { //correct
OR else simply change the prop name as below
<Agregar inputPregunta={this.actualizarPregunta} validatePregunta={this.state.validatePregunta}/>
And you should change actualizarPregunta
once you update the state it's not updating the state value real time, its a async process, so this.state.inputPregunta.trim()
will give you the value just before the update, so change it like this, and i love the way @Drew Reese handle this part
actualizarPregunta = (e) => {
const newValue = e.target.value;
this.setState({inputPregunta: newValue })
if(newValue.trim().length > 0){
this.setState({validatePregunta: true})
} else {
this.setState({validatePregunta: false})
}
}