How to add a React component when a button is clicked?

I would like to have a button Add inputthat, when clicked, will add a new component Input. Below is the React.js code, which I thought was one way to implement the logic I want, but unfortunately it doesn't work.

The exception I received is: invariant.js:39 Uncaught Invariant Violation: Objects are not valid as a React child (found: object with keys {input}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of `FieldMappingAddForm`.

How to solve this problem?

import React from 'react';
import ReactDOM from "react-dom";


class Input extends React.Component {
    render() {
        return (
            <input placeholder="Your input here" />
        );
    }
}


class Form extends React.Component {
    constructor(props) {
        super(props);
        this.state = {inputList: []};
        this.onAddBtnClick = this.onAddBtnClick.bind(this);
    }

    onAddBtnClick(event) {
        const inputList = this.state.inputList;
        this.setState({
            inputList: inputList.concat(<Input key={inputList.length} />)
        });
    }

    render() {
        return (
            <div>
                <button onClick={this.onAddBtnClick}>Add input</button>
                {this.state.inputList.map(function(input, index) {
                    return {input}   
                })}
            </div>
        );
    }
}


ReactDOM.render(
    <Form />,
    document.getElementById("form")
);
+4
source share
1 answer

Remove {}., No need to use it in this case

{this.state.inputList.map(function(input, index) {
  return input;
})}

Example

or is it better to avoid .mapand just use in this case {this.state.inputList},

Example

+7
source

All Articles