Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
111
rated 0 times [  112] [ 1]  / answers: 1 / hits: 84147  / 8 Years ago, sat, april 9, 2016, 12:00:00

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?


More From » reactjs

 Answers
11

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(prevState => ({ inputs: prevState.inputs.concat([newInput]) }));
}
}


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


[#62642] Wednesday, April 6, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaylynkarinam

Total Points: 740
Total Questions: 103
Total Answers: 103

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;