Just practicing with intro React Use State and can't figure out what is wrong here when attempting to add a counter and a random user number generator button
Here is the code
import React, { useState } from 'react'
import './App.css';
import Projects from './components/Projects';
import List from './components/List';
import Resume from './components/Resume';
import Bio from './components/Bio';
const App = () => {
let [count, setCount] = useState(0)
let [userNames, setUserNames] = useState(['shannonYoung', 'zoraJackson', 'giavannaClark'])
let [userNameIndex, setUserNameIndex] = useState(0)
const increment = () => {
setCount(count 1)
}
const decrement = () => {
setCount(count - 1)
let [userNameIndex, setUserNameIndex] = useState(0)
const randomUserNameIndex = () => {
let randomNum = Math.floor(Math.random() * userNames.length)
setUserNameIndex(randomNum)
}
}
return (
<>
<h1>My Portfolio</h1>
<p> test count: {count}</p>
<button onClick={increment}> </button>
<button onClick={decrement}>-</button>
<h2>Hello {userNames[userNameIndex]}</h2>
<button onClick={randomUserNameIndex}> Change User </button>
<Projects />
<List />
<Resume />
<Bio />
</>
);
}
export default App;
Here is the error I'm getting:
Compiled with problems:X
ERROR
[eslint] src/App.js Line 22:45: React Hook "useState" is called in function "decrement" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use" react-hooks/rules-of-hooks Line 37:24: 'randomUserNameIndex' is not defined no-undef
Search for the keywords to learn more about each error.
CodePudding user response:
Remove this line
let [userNameIndex, setUserNameIndex] = useState(0)
from decrement
function. As the error message says, hooks are supposed to be defined either at the component level, or in another hook. You need the former.
CodePudding user response:
When you add an onClick function you want to wrap it in a callback function like this. Then it should work. Also as above answer states remove your hook definitions from the increment function. You can only define hooks at the top level (It seems you have defined the same hook twice). Let me know!
<button onClick={() => increment()}> </button>
<button onClick={() => decrement()}>-</button>
<button onClick={() => randomUserNameIndex()}> Change User </button>