How to add a component to each click on the react

1

I have a form where it has a standard responsible (NewResponsavel), but if there is any other has to be added a new responsible with each click of the 'add another' button, today I can only add once, if someone would know how to add the same component several times.

New Responder 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>  

 );
}

    
asked by anonymous 12.03.2018 / 21:23

1 answer

1

You should create a list (save in 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>
    );
  }
}
    
12.03.2018 / 21:57