Rowandinho
Rowandinho

Reputation: 203

Adding an item to a list in React

I want to add a new fruit to the current list of fruit but I am unsure how to go about doing it, I am currently posting an empty string on submit, which just adds an empty string li to the list

my fruit list component is as follow;

import AddFruit from './AddFruit';

class Fruits extends Component {
  state = {
    fruits: ['apple', 'banana']
  };

  render() {
    const { fruits } = this.state;
    return (
      <div style={{ paddingTop: 30 }}>
        <AddFruit handleSubmit={this.handleSubmit} />
        {fruits.map(fruit => {
          return (
            <ul key={fruit}>
              <li>{fruit}</li>
            </ul>
          );
        })}
      </div>
    );
  }

  handleSubmit = e => {
    const { fruits } = this.state;
    e.preventDefault();
    this.setState({ fruits });
  };
}

export default Fruits;

and my fruit adder is as follows... I know they are totally wrong but I'm having a tough time figuring this out and its late :(


class AddFruit extends Component {
  state = {
    addItem: ''
  };
  render() {
    const { addItem } = this.state;
    return (
      <div>
        <form onSubmit={this.handleSubmit} style={{ paddingTop: 35 }}>
          <input
            type="text"
            value={addItem}
            placeholder="Add Item"
            onChange={this.handleChange}
          />
          <button
            onClick={this.props.handleSubmit}
            className="btn btn-primary btn-sm"
          >
            Add Fruit
          </button>
        </form>
      </div>
    );
  }

  handleChange = event => {
    console.log(event.target.value);
    const { value } = event.target;
    this.setState({ addItem: value });
  };
}

export default AddFruit;

Upvotes: 1

Views: 2623

Answers (2)

Melchia
Melchia

Reputation: 24244

This is a problem on how to pass data from child component to its parent in ReactJS:

Fruits

  <AddFruit onFruitsChange={this.onFruitsChange} />

  onFruitsChange = fruit => {
    const { fruits } = this.state;
    fruits = [ ...fruits, fruit]
    this.setState({ fruits });
  };

AddFruit

<button
        onClick={this.onAddFruit}
        className="btn btn-primary btn-sm"
      >

  onAddFruit = (e) => {
    e.preventDefault();
    const fruit = this.state.addItem;
    this.props.onFruitsChange(fruit)
  };

Upvotes: 0

Dmitry Reutov
Dmitry Reutov

Reputation: 3032

it is not clear what kind of element invokes HandleSubmit, but lets say it is input so the code is

handleSubmit = e => {
  e.preventDefault();
  const fruitName = e.target.value;
  const fruits = [...this.state.fruits, fruitName];
  this.setState({ fruits });
};

Upvotes: 1

Related Questions