Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add React component on button click?

I would like to have an Add input button that, when clicked, will add a new Input component. The following is the React.js code that I thought is one way of implementing the logic that I want, but unfortunately it's doesn't work.

The exception that I got 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 do I 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")
);
like image 802
hans-t Avatar asked Mar 31 '16 14:03

hans-t


People also ask

How do I add a component to button click React?

Adding Components on Button Click It's time to implement the creation of new elements when we click the 'Call Component' button. import { useState } from 'react'; import { Button } from './Button. js'; import { ListComponent } from './ListComponent.


1 Answers

React Hook Version

Click here for live example

import React, { useState } from "react";
import ReactDOM from "react-dom";

const Input = () => {
  return <input placeholder="Your input here" />;
};

const Form = () => {
  const [inputList, setInputList] = useState([]);

  const onAddBtnClick = event => {
    setInputList(inputList.concat(<Input key={inputList.length} />));
  };

  return (
    <div>
      <button onClick={onAddBtnClick}>Add input</button>
      {inputList}
    </div>
  );
};

ReactDOM.render(<Form />, document.getElementById("form"));
like image 158
Jonathan Avatar answered Oct 13 '22 16:10

Jonathan