-2

When I click on the add button, it should add an input and I have to save it.

Something like this but with Input. But the problem is the input are all different so that's why I don't know how to do

My code :

class Main extends Component {
  constructor(props) {
    super(props);
    this.handleChangeCategorie = this.handleChangeCategorie.bind(this);
    this.state = {
      // I think it should be an array but I don't know
      valueCategorie: ""
    };
  }
  addCategorie(){
    //Something to add input 
  }
  handleSubmit() {
    //Make something with the categorie
  }

  handleChangeCategorie(e) {
    // I don't know if I can use this function for all Input
    this.setState({ valueCategorie: e.target.value });
  }
  render() {
    return <div className="container">              
        <input type="text" value={this.state.valueCategorie} onChange={this.handleChangeCategorie} />
        <Button onClick={this.addCategorie}>Add Input</Button>
        <Button onClick={this.handleSubmit}>Send</Button>
      </div>;
  }
}

I don't think it's the same question here because he uses something to count. Maybe there is an other way to it ? Or is it the only way ?

Monsieur Sam
  • 333
  • 1
  • 6
  • 20
  • How is this different from the linked question? – VTodorov May 29 '18 at 11:47
  • 1
    Just take the example you provided and change with inputs. You can keep an array of JSX elements and render it to the page. When a user clicks add, just push new input to that array. – Javid Asgarov May 29 '18 at 11:48
  • Possible duplicate of [Add Inputs in React with add button](https://stackoverflow.com/questions/45543419/add-inputs-in-react-with-add-button) – VTodorov May 29 '18 at 11:49

1 Answers1

1

Say you have an array of your different inputs,

let inputArray = [<input id="1"/>,<input id="2"/>,<input id="3"/>]

Declare state, state={ inputsRenderingArray:[] }

Functions to add the input dynamically,

AddFirst=()=>this.setState({inputsRenderingArray:[...this.state.inputsRenderingArray, inputArray[0]]})

AddSecond=()=>this.setState({inputsRenderingArray:[...this.state.inputsRenderingArray, inputArray[1]]})

AddThird=()=>this.setState({inputsRenderingArray:[...this.state.inputsRenderingArray, inputArray[2]]})

in the render, onclick of add button push these items into the renderable array, render(){

return(
   <Button onClick={AddFirst}>Add First</Button>
   <Button onClick={AddSecond}>Add Second</Button>
   <Button onClick={AddSecond}>Add Second</Button>

   {this.state.inputsRenderingArray}
)

}
Rohith Murali
  • 5,551
  • 2
  • 25
  • 26