0
I’m a beginner with React and I’m having a hard time recovering the value of a props, in a child component. I have a component called Search, which when clicking a button, I pass via props the value to another component, which I called Map I can recover the value, but only within the method render. How I retrieve the value and assign it to another variable for example or state so I can use it in some other method?
Busca.js:
import React, { Component } from 'react';
import Mapa from './Mapa';
class Busca extends Component {
constructor(props){
super(props);
this.state = {
input: '',
cep: ''
};
this.buscarEndereco = this.buscarEndereco.bind(this)
}
buscarEndereco(){
this.setState({
input: '',
cep: this.state.input
});
}
updateInputValue(evt) {
this.setState({
input: evt.target.value
});
}
render() {
return (
<div className="container">
<h3>Consultade endereço</h3>
<div className="col-md-6 jumbotron">
<div className="form-group row">
<div className="col-sm-12">
<p><strong>Consultar</strong></p>
</div>
<label for="colFormLabel" className="col-sm-2 col-form-label">CEP</label>
<div className="col-sm-5">
<input value={this.state.input} type="text" onChange={evt => this.updateInputValue(evt)} className="form-control" />
</div>
<div className="col-sm-3">
<input type="button" onClick={this.buscarEndereco} value="Buscar" className="btn btn-primary"/>
</div>
</div>
</div>
<Mapa cep={this.state.cep}/>
</div>
);
}
}
export default Busca;
Mapa.js
import React, { Component } from 'react';
class Mapa extends Component {
constructor(props){
super(props);
}
render() {
return (
<div>
<h1>Mapa {this.props.cep}</h1>
</div>
);
}
}
export default Mapa;
"I can recover the value, but only within the render method" - how so ? In the component
Mapa
,this.props.cep
will work in any method– Isac
So, it turns out that I need to assign this.props.cep to a variable to do a query on the API, only I’m not sure how to do it
– Daniel Swater
Just do
let minhaVar = this.props.cep;
in any class methodMapa
. I can’t understand the difficulty.– Isac
No, man, it doesn’t work because there’s the component life cycle thing. When I type something and press the button, this.props.zip is stunned, beauty. But I need that for every click, I can recover out of the render, I needed to pass as if it were a state entedeu?
– Daniel Swater
Unfortunately I could not notice. If the goal is to change state then you have to use
this.setState
and notprops
. I think it’s best to exemplify the line of code you’re trying to get that value from. Put it exactly as you tried and it didn’t work.– Isac
Okay, I’ll edit the code and add comments
– Daniel Swater