i am beginner and trying to refactor Javascript hooks into Typescript but i cannot get button onClick event to change state. Can you please help?
This is useToggler component
import {useState} from 'react'
function useToggler (defaultOnValue=false){
const[istoggledOn, setIsToggledOn] = useState(defaultOnValue);
function clickHandler(){
setIsToggledOn(prevState => !prevState)
}
return [istoggledOn, clickHandler]
}
export default useToggler
and this is App component
import * as React from 'react';
import './App.css';
import useToggler from './compononets/useToggler'
const App: React.FC = () => {
const[show, toggle]=useToggler(true);
return (
<div className="App">
<button onClick={()=>toggle}>+</button>
<span>{show? "yes!": "no!"}</span>
</div>
);
};
export default App;
onClick={() => toggle()}(or, better yet,onClick={toggle}. This would not have worked even without TypeScript, so it's not the language migration making it difficult.onClick={toggle}, notonClick={()=>toggle}.onClick={()=>toggle}setsonClickto a function that returns theclickfunction as its return value.onClick={toggle}setsonClicktotoggle.