How to add a Component to each click on the React

Asked

Viewed 1,926 times

2

I have a form where there is a responsible pattern (Novoresponsavel), but if there are some other have to be added a new responsible at each click of the 'add another' button, today I can only add a single time, I would like to know if anyone could add a same Component several times.

New Responsavel is a Component - which has 4 inputs inside it, I just want to repeat the Component.

import {NovoResponsavel} from 'components';

class NovoAtendimento extends React.Component {

handleClick() {
  this.setState({
    clicked: true
  });
}
render(){

 return (
    <NovoResponsavel/>

    {this.state.clicked ? <NovoResponsavel /> : null}

    <ItemGrid xs={12} sm={12} md={12}>
       <a onClick={this.handleClick} className="addnew">
         adicionar outro responsável
       </a>   
    </ItemGrid>  

 );
}

inserir a descrição da imagem aqui

1 answer

3


You must create a list (save to state) and use the map to render this list:

class NovoResponsavel extends Component {
  render(){
    const responsavel = this.props.responsavel;

    return (
       <div>
         Responsavel <input type="text" defaultValue={responsavel.Nome} />
        </div>   
    );
   }
}

class NovoAtendimento extends Component {
  constructor(props){
    super(props);
    this.state = {responsaveis: []};
    this.handleAdicionarResponsavel = this.handleAdicionarResponsavel.bind(this);
  }
   handleAdicionarResponsavel() {
    var responsaveis = this.state.responsaveis;
    responsaveis.push({Nome: ''});

    this.setState({
      responsaveis: responsaveis
    });
  }
  render(){
    const responsaveis = this.state.responsaveis.map(r=> <NovoResponsavel responsavel={r}/>);

    return (
      <div>
        {responsaveis}
        <ItemGrid xs={12} sm={12} md={12}>
          <a onClick={this.handleAdicionarResponsavel} className="addnew">
            adicionar outro responsável
          </a>   
          </ItemGrid>  
        </div>
    );
  }
}
  • Good answer. Also explain to the AP why it does not work as a boolean as it has.

Browser other questions tagged

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