A
A
arishaYako_142020-07-09 14:16:09
React
arishaYako_14, 2020-07-09 14:16:09

How to add a new component with every input in React?

I'm making a small Trello clone type workout app. I need, when I enter something into the form and click on ''create'', I need a new component to appear with a title in the form of this input. The problem is that I need more components to appear with each new input, I just can’t do it.
Here is how I am trying to do it:

import React, {Component} from 'react';
import './AddForm.css';
import TaskBoard from '../TaskBoard/TaskBoard';

export default class AddForm extends Component{
    constructor(props){
        super(props);
        this.state = {
            input: '',
            obj: [],
            
        }
        this.onHandleChange = this.onHandleChange.bind(this);
        this.onHandleSubmit = this.onHandleSubmit.bind(this);
    }

    onHandleChange(e){
        this.setState({
            input: e.target.value
        });
        
    }

   onHandleSubmit(){
        this.state.obj.push(this.state.input);
        this.setState({
            input: ''
        })
   }

   

    render(){
        return(
            <div className = 'adder'>
                <h1 className = 'header'>Enter the type of tasks you need to be done:</h1>
                <div>
                <form>
                    <input className = 'board-add'  onSubmit = {this.onHandleSubmit} onChange = {this.onHandleChange} type = 'search' name = 'textarea' placeholder = 'How shall we call the board?'/>
                    <p><button className = 'cancel'>CANCEL</button>
                    <button onClick = {this.onHandleSubmit} className = 'create'>CREATE</button></p>
                </form>
                </div>
                {this.state.obj.map((item) => <TaskBoard taskType = {item} />)}
            </div> 

        );
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Cheryabushkin, 2020-07-09
@arishaYako_14

You can’t write like this , you must always use it to update the state . And to render components using a loop, you need to additionally write a function like thisthis.state.obj.push(this.state.input)setState({})

createTaskBoard = () => {
    return this.state.obj.map((item) => <TaskBoard taskType = {item} />)
}

render () {
    return (
        <div className = 'adder'>
            // ... ваш код
            { this.createTaskBoard() }
        </div>
   )
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question