Home > Net >  TS2322: Type 'Count' is not assignable to type 'ReactNode'
TS2322: Type 'Count' is not assignable to type 'ReactNode'

Time:05-15

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;

CodePudding user response:

Should be {count.count} as count is an object ({count:0})

<div>Count <span>{count.count}</span> </div>

CodePudding user response:

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>
  • Related