Recover value of a props in child component

Asked

Viewed 1,287 times

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

  • 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

  • Just do let minhaVar = this.props.cep; in any class method Mapa. I can’t understand the difficulty.

  • 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?

  • Unfortunately I could not notice. If the goal is to change state then you have to use this.setState and not props. 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.

  • Okay, I’ll edit the code and add comments

Show 1 more comment

2 answers

1

You can set a state in the Map component:

this.state = { cep: '' };

and in the method render before the return check whether the status value cep of the component is different informed by props if it is will update the status:

(this.state.cep !== this.props.cep) && this.setState({cep: this.props.cep});

Working example

class Mapa extends React.Component {

  constructor(props) {
    super(props);
    this.state = { cep: '' };
  }

  metodoA = _ => {
    alert(this.state.cep);
  }

  render() {
    (this.state.cep !== this.props.cep) && this.setState({cep: this.props.cep});
    return (
      <div>
        <h1>Mapa {this.state.cep}</h1>
        <button onClick={this.metodoA}>Exibir Mensagem</button>
      </div>
    );
  }
}

class Busca extends React.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>
    );
  }
}

class App extends React.Component {
  render() {
    return (
      <div>
        <Busca />
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

  • Thanks, as soon as I get home I’ll test

0

You have access to the ZIP code within the component that instantiates the MAP and the ZIP code. Inside the MAPA you have access to the value of the CEP tbm.

Your problem is: Before rendering the map you need to validate the zip, and or call an api.

In my view: the value of the cep is in the state of the container/Component/view, when this value changes, you must call the api inside this one as soon as you click the button.

Your button should call the api by passing the value of the cep. if it returns the right one, pass this value to the map, otherwise the error.

I also believe that your code is a prototype of how everything will work, because your map should be a functional component, your zip code as well, and only the component that uses ZIP code and MAPA could be a stateful component or not. In practical ways, only the component that would be the VIEW should be steteful or should have very strong reason for a single component to be a Component class.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.