1
votes

why do I get the above error in React? - if I take out the useState for 'count2' in Person.js it works well - but surely this should work?

I've got two files: Persons.js that renders a list of Person.js. 'people' array is passed in

import React, { useEffect, useRef, useContext, useState } from 'react';
import Person from './Person/Person';

const Persons = (props) => {

    const [count, setCount] = useState(0);
    const [people, setPeople] = useState([]);

    useEffect(() => {
        setPeople(props.people);
    },
        []      // this to ensure a one-off!
    ); 

    let increaseMe = () => {
        setCount(count + 1);
    }

    let clickA = (event ) => {
        let newPeople = [...people];
        newPeople.push({ name: 'Tom', age: 16 })
        setPeople(newPeople);
    }

    let list = people.map(p => Person({name: p.name, 'age': p.age}));

    return (
        <React.Fragment>
            <div>Hello Persons - { props.message } </div>
            <button className='btnStyle' onClick={increaseMe}>IncreaseMe</button> { count }
            <button onClick={clickA}>click A</button>
            { list }
        </React.Fragment>
    )
}

export default Persons;
import React, { useState } from 'react';

const Person = props => {

    const [count2, setCount2] = useState(0);

    return (
        <div key={props.name}>
            { props.name } - { props.age} - { count2 }
        </div>
    )
}

export default Person;
2

2 Answers

2
votes

try this :

let list = people.map(p => <Person key={p.name} name={p.name} age={p.age} );

And the key is not necessary on your Person component.

2
votes

The error comes from this line:

let list = people.map(p => Person({name: p.name, 'age': p.age}));

That's not how you render components in React, what you done is to call a function named Person, you want to call React.createElement instead (render a function component), which is just a JSX:

let list = people.map(p => <Person key={p.id} name={p.name} age={p.age} />);

Of course, if you want to call a function which returns JSX, you can't use hooks in it, because hooks are ONLY for function components (read about Rules Of Hooks).