score:2

Accepted answer
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app'/>

score:0

class Module extends Component {
    constructor() {
        super()

        this.state = {
            inputs: [
                { type: 'text', placeholder: 'placeholder text', name: 'text1', id: 'text1', value: 'aaa' },
                { type: 'text', placeholder: 'another placeholder text', name: 'text2', id: 'text2', value: '' },
                { type: 'text', placeholder: 'third placeholder text', name: 'text3', id: 'text3', value: '' },
            ]
        }

        this.handleInputChange = this.handleInputChange.bind(this)
        this.saveModule = this.saveModule.bind(this)
    }

    // change this to an arrow function
    handleInputChange = (event) =>  {
        const name = event.target.name;
        const value = event.target.value;
        const oldInputState = this.state.inputs.find(i => i.name === name);
        // use the spread operator or Object.assign to create a brand new state object
        this.setState({
            ...,
            this.state, // copy everything from the old state
            // expect change the `inputs` value
            {inputs: [ // create a brand new array
                ...this.state.inputs.filter(i => i.name !== name),
                {...oldInputState, value} // replace old value with the new value
                // refer to that video I included, it's a great explanation
            ]}
        });
    }

    renderInput = (input) => {
        return(
            <div key={ input.id }>
                <input
                    type={ input.type }
                    name={ input.name }
                    placeholder={ input.placeholder }
                    onBlur={ this.saveModule }
                    value={ input.value }
                    onChange={ this.handleInputChange }
                />
            </div>
        )
    }

    render() {
        return (
            <div>
                { this.state.inputs.map(this.renderInput) }
            </div>
        )
    }
}

export default Module

Related Query

More Query from same tag