'TS2322: Type 'Count' is not assignable to type 'ReactNode'
I am new in react and TS and I need help I am trying to use useState with typescript
import React,{useState} from 'react'
interface Count{
count: number
}
const App = () =>{
const [count,setCount] = useState<Count>(
{
count:0
})
return (
<div>
<div>Count <span>{count}</span> </div>
</div>
)
}
export default App;
Solution 1:[1]
Should be {count.count}
as count
is an object ({count:0}
)
<div>Count <span>{count.count}</span> </div>
Solution 2:[2]
Your state is currently an object. This is uncommon in react function components (since you can call useState
as many times as you need to), so unless there's a reason to do it with an object, i would recommend making it a number:
const [count, setCount] = useState(0);
Or with an explicit type:
const [count, setCount] = useState<number>(0);
If you do need your state to be an entire object, then make sure to pluck out the number and put that on the page, not the full object:
<span>{count.count}</span>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Aseem Gautam |
Solution 2 |