jayasth jayasth - 5 months ago 237
Javascript Question

React: dynamically add input fields to form

I am using formsy-react for the form, I want to render more options when an event is fired, code looks something like this:

class MultipleChoice extends Component {
constructor(props) {
super(props);

}

render() {

return(
<div>
<Form>
<div id="dynamicInput">
<FormInput />
</div>
</Form>
</div>
);

}
}


I have a button and onClick event I want to fire a function that appends another into div id "dynamicInput", is it possible?

Answer

Yes, we can update our component's underlying data (ie state or props). One of the reasons React is so great is that it allows us to focus on our data instead of the DOM.

Let's pretend we have a list of inputs (stored as an array of strings in state) to display, and when a button is clicked we add a new input item to this list:

class MultipleChoice extends Component {
    constructor(props) {
        super(props);
        this.state = { inputs: ['input-0'] };
    }

    render() {
        return(
            <div>
               <Form>
                   <div id="dynamicInput">
                       {this.state.inputs.map(input => <FormInput key={input} />)}
                   </div>
               </Form>
               <button onClick={ () => this.appendInput() }>
                   CLICK ME TO ADD AN INPUT
               </button>
            </div>
        );
    }

    appendInput() {
        var newInput = `input-${this.state.inputs.length}`;
        this.setState({ inputs: this.state.inputs.concat([newInput]) });
    }
}

Obviously this example isn't very useful, but hopefully it will show you how to accomplish what you need.