1

I have this structure.

<PlayerFormBox>
   - <PlayerForm>

I add new form dynamic, I want to know how I can get hold of all input values from the form in PlayerFormBox on submit

<PlayerFormBox> 
....

render: function () {
    var formFields = [];
    for(i = 0; i < this.state.numOfPlayers; i++){
        formFields.push(<PlayerForm key={i} />);
    }
    return (
        <div className="playerBox">
            <input value="add field" type="button" onClick={this.addField} />
            <form id = "form" onSubmit={this.handleSubmit}>
                {formFields}
                <input type="submit" value="submit" />
            </form>
        </div>
    );
}



<PlayerForm>

var PlayerForm = React.createClass({
render: function () {
    return (
        <div>
            <input key={this.props.index} type="text" name="name">
        </div>
    );
})

1 Answer 1

1

You should probably make the PlayerForm component to trigger an event when the value changes and store these values in the PlayerFormBox's state. This way you'll have all the values upon submission. In fact, for React, it's a good practice not to submit forms directly. It's a good practice to use your input fields to build a model and then process and submit this model, via Ajax, using a request library that works on the browser like axios.

So, in the PlayerForm, make it to trigger an event:

var PlayerForm = React.createClass({

handleChange: function(event) {
    // it's passing the index and the value as parameters
    this.props.onChange(this.props.index, event.value);
}

render: function () {
    return (
        <div>
            <input key={this.props.index} onChange={handleChange} type="text" name="name">
        </div>
    );
})

Now, create a PlayerFormChanged function on the PlayerFormBox, then pass it as a handler when you create a new PlayerForm:

for(i = 0; i < this.state.numOfPlayers; i++){
    formFields.push(<PlayerForm key={i} onValueChange={onPlayerFormValueChange}/>);
}

Now in the onPlayerFormValueChange function, build a model, something like this:

onPlayerFormValueChange: function(index, value) {
     // now you should set this.state.model[index] = value
     // Use the imutability helpers here: https://facebook.github.io/react/docs/update.html
     // this will result on a setState that will render everything again accordingly 
}

Now, upon submission, PlayerForm has the model on it's state.

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.