Hello Guys, I am a beginner in learning Javascript. I am having trouble with my code. I just hope that I will get some help with better understanding.
import React, { useState } from "react"
function LetsseeOnchange() {
const [names, setNames] = useState([]);
function addName() {
const newName = [...names]
if (newName.length > 0) {
setNames([...names, newName]);
setNames("");
}
}
return (
<div>
<input value={names} onChange={e => setNames(e.target.value)} />
<button onClick={addName}>Add Name</button>
<ul>
{names.map((item, index) => <li key={index}>{item}</li>)}
</ul>
</div>
);
}
export default LetsseeOnchange;
The moment I typed a word in the box, it showed an error in the console.
1 Like
so when you put something in the box, you set names
to the value of that box. Which is a string.
A string cannot be map
’d. map
is for arrays.
1 Like
It’s been a while since I have looked at React, so my knowledge is somewhat basic.
A bit of trial and error and some small changes to your script.
import React, { useState } from "react";
import "./style.css";
export default function App() {
const [names, setNames] = useState([]); // names is an array
const [name, setName] = useState(''); // name is a string
const addName = (name) => {
setNames((names) => [...names, name]);
}
return (
<div>
<input value={name} onChange={(evt) => setName(evt.target.value)} />
<button onClick={() => addName(name)}>Add Name</button>
<ul>
{
names.map(
// anti-pattern using index as key
(item, index) => <li key={index}>{item}</li>
)
}
</ul>
</div>
);
}
It works, but no doubt there is a better way of doing this.
With regards using indexes as key values
system
Closed
4
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.