0

Problem

It's not showing the elements within the item. It doesn't render anything at the moment.

List.js

import React from 'react';

const List = props => (
  <div>
    {
      props.items.map((item, index) => {
      return <div key={index}>
          <h1>{item.name}</h1>

          <p>{item.term}</p>

      </div>
    })}
  </div>
);

export default List;

App.js

import React, {Component} from 'react'
import './App.css'
import List from './List';

class App extends Component {

    constructor(props) {
        super(props);

        this.state = {
            term: '',
            name: '',
            items: []
        };
    }

    onChange = (event) => {
        const { name, value } = event.target;
        this.setState({ [name]: value });

    }

    onSubmit = (event) => {
        event.preventDefault();

        this.setState({
            term: '',
            name: '',
            items: [
                ...this.state.items,
                this.state.term,
                this.state.name
            ]
        });

    }

    render() {
        const { term, name, items } = this.state;
        return (
          <div>
                <form className="App" onSubmit={this.onSubmit}>
                    <input name="term" value={this.state.term} onChange={this.onChange}/>
                    <input name="name" value={this.state.name} onChange={this.onChange}/>
                    <button>Submit</button>
                </form>


              <List items={this.state.items} />

            </div>
        );
    }

}

1 Answer 1

1

Issue was in onSubmit, you need to convert to object and than add

onSubmit = event => {
    event.preventDefault();

    this.setState({
      term: "",
      name: "",
      items: [...this.state.items, { term: this.state.term, name: this.state.name}]
    });
    setTimeout(() => { console.log(this.state.items) }, 0)
  };

https://codesandbox.io/s/p7p128w7mx

Sign up to request clarification or add additional context in comments.

3 Comments

let me give this a shot.
This works thanks, so i just need to convert to object then add, now i see.
Cheers @BARNOWL:)

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.