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

3
  • How is this different from the linked question? Commented May 29, 2018 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. Commented May 29, 2018 at 11:48
  • Possible duplicate of Add Inputs in React with add button Commented May 29, 2018 at 11:49

1 Answer 1

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}
)

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.