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 I click on a button, I pass via the value props to another component, which I called Map I can retrieve the value, but only within the render method. How do I retrieve the value and assign it to another variable by example or state so that I can use it in some other method?
Search.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;
Map.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;