I want to render the information contained in an object. So I use the map method like this,
<ul>
{persons.map(person => <li key={person.id}> person.name </li>)}
</ul>
In VS code and console on the browser, there were no error. But in the main screen it display ‘person’ is not defined. As far as I know, I am executing the map method correctly. How can I fix this ? Here are the rest of the code. How can
App.js
import { useState } from 'react'
const App = () => {
const [persons, setPersons] = useState([
{
name: 'Arto Hellas',
id: 1
}
])
const [newName, setNewName] = useState('')
const addName = (event) => {
event.preventDefault()
const nameObject = {
name: newName,
id: persons.length + 1
}
setPersons(persons.concat(nameObject))
setNewName('')
}
console.log(persons)
const handleNameChange = (event) => {
setNewName(event.target.value)
}
return (
<div>
<h2> Phonebook </h2>
<form onSubmit={addName}>
<div>
name: <input value={newName} onChange={handleNameChange} />
</div>
<div>
<button type="submit"> add </button>
</div>
</form>
<h2> Numbers </h2>
<ul>
{persons.map(person => <li key={person.id}> person.name </li>)}
</ul>
</div>
)
}
export default App
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')).render(<App />)
4
Answers
You need to change
person.name
to{person.name}
Mistake with using persone inside
<li/>
And its works. I didint see ‘A variable(‘person’) is not defined’ in errors
https://codesandbox.io/s/inspiring-thompson-7f6hqj?file=/src/App.js
You’re missing on minor code details.
Remember to put inside a JSX element the variables of the component between "{}".