score:0

const Input = props => (
  <div className="answer-choice">
    <input type="text" className="form-control" name={props.index} />
    <div className="answer-choice-action">
      <i onClick={props.addInput}>add </i>
      <i>Remove</i>
    </div>
  </div>
);

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      choices: [],
      nrOfElements: 0
    };
  }

  addInput = index => {
    this.setState(prevState => {
      const choicesCopy = [...prevState.choices];
      choicesCopy.splice(index, 0, `input_${prevState.nrOfElements}`);
      return {
        choices: choicesCopy,
        nrOfElements: prevState.nrOfElements + 1
      };
    });
  };

  componentDidMount() {
    this.addInput(0);
  }

  render() {
    return (
      <div>
        {this.state.choices.map((name, index) => {
          return (
            <Input
              key={name}
              addInput={() => {
                this.addInput(index);
              }}
              index={index}
            />
          );
        })}
      </div>
    );
  }
}

Related Query

More Query from same tag