type hereimport './App.css';
import { useState } from 'react';
function App() {
const [text, setText] = useState()
const People = {
name: 'jack'
}
const peoples = People.map(() => ({
nick: People.name
})
)
const funct = () =>{
if (text === peoples.nickname) {
console.log('worked')
} else {
console.log('not worked')
}
}
return (
<div>
<input onChange={(event) => {setText(event.target.value)}}/>
<h1>{text}</h1>
<br />
<button onClick={funct}>Click</button>
</div>
);
}
export default App;
I'm hoping that you can solve my question,and show my at what point am i wrong. Thank you very much. I've just tried to map the text and it still doesn't work and also i've tried to make the text as an object but it still doesn't work.
CodePudding user response:
You are comparing an array with a string and because of this, it's not working.
you need to update your funct
to something like this:
const funct = () =>{
peoples.forEach((p) => {
if (p.nickname === text) {
console.log('worked')
} else {
console.log('not worked')
}
})
}
CodePudding user response:
When trying to create a array of people you try to use map on a object. This is not possible since you can only use map
on a array.
To fix this you could do something like this to create a array with a new object in it which contains a property nick
with the value of People.name
const peoples = [{ nick: People.name }];
Then in the if statement you're checking for peoples.nickname
while we just created a object with a property called nick
.
if (text === peoples.nick) {
...
}
Now this in not yet going to work. Like mentioned in the comments you're comparing a string with a array. To solve this you can use some kind of loop
const funct = () => {
for (const people of peoples) {
if (text === people.nick) {
console.log("worked");
} else {
console.log("did not work");
}
}
};
Or we can use the every function to check if all the people in the array have match the text
value
const funct = () => {
const allPeoplesValidNick = peoples.every((people) => people.nick === text);
if (allPeoplesValidNick) {
console.log("worked");
} else {
console.log("not worked");
}
};