Home > Net >  Why there is an extra name to array stored in state
Why there is an extra name to array stored in state

Time:10-06

Having this code with one parent component (app) and two children (Inputs, List). Inputs is for writing data, a callback from parent is saving it to a people array which writes that data in List component.

My question is, why do it requires people.people.map(...) instead of people.map(...)? And how can it be fixed that.

import React from 'react';
import './App.css';
import Inputs from './components/Inputs';
import List from './components/List';
import { useState } from 'react';

function App() {
  const [person, setPerson] = useState({ name: '', email: '' });
  const [people, setPeople] = useState([]);

  const callback = (e) => {
    setPeople((people) => [...people, person]);
  };

  return (
    <div>
      <Inputs callback={callback} person={person} setPerson={setPerson} />
      <List people={people} />
    </div>
  );
}

export default App;

Inputs:

const Inputs = ({ person, setPerson, callback }) => {
  const updateName = (e) => {
    setPerson((person) => ({ ...person, name: e.target.value }));
  };

  const updateEmail = (e) => {
    setPerson((person) => ({ ...person, email: e.target.value }));
  };

  return (
    <div>
      <label>name:</label>
      <input onChange={updateName}></input>
      <label>email:</label>
      <input onChange={updateEmail}></input>
      <button onClick={() => callback(person)}>add person</button>
    </div>
  );
};

export default Inputs;

List:

const List = (people) => {
  return (
    <div>
      {people.people.map((p) => ( // <---- HERE
        <div>
          <span>{p.name}</span>
          <span>{p.email}</span>
        </div>
      ))}
    </div>
  );
};

export default List;

CodePudding user response:

Because you name props to people in List component

You may change like this


const List = (props) => {
  return (
    <div>
      {props.people.map((p) => ( // <---- HERE
        <div>
          <span>{p.name}</span>
          <span>{p.email}</span>
        </div>
      ))}
    </div>
  );
};

export default List;

or this


const List = ({people}) => {
  return (
    <div>
      {people.map((p) => ( // <---- HERE
        <div>
          <span>{p.name}</span>
          <span>{p.email}</span>
        </div>
      ))}
    </div>
  );
};

export default List;
  • Related