I recently started using typescript and I'm having trouble with passing a use state setter function,
my parent component is is this :
const [word, setword] = useState('run')
and in the child im passing :
<Child word={word} setword={setword}/>
the child has this :
interface Props {
word: string
setword: React.Dispatch<React.SetStateAction<string>>;
}
const VoicetoText: React.FC<Props> = (word, setword) => {
return (
{word}
<button onClick={()=>setword('hey buddy')} ><button/>
)}
CodePudding user response:
You forgot to add a curly brace to
const VoicetoText: React.FC<Props> = (word, setword)
either use props or deconstruct the props
const VoicetoText: React.FC<Props> = (props)
props.setWord
deconstruct
const VoicetoText: React.FC<Props> = ({word, setword})
CodePudding user response:
Just use setword: (word: string) => void
as the prop type.
interface Props {
word: string
setword: (word: string) => void;
}
CodePudding user response:
I would suggest to not make your life harder and go wtih something like:
const Child = ({setWord}: {setWord: (arg0: string}) => void) => {
// () => setWord("word") is jsut for sample sake, you should avoid using arrow function calls inside event handleres like this
return <button onClick={() => setWord("word")}>Click me</button>
}
const Parent = () => {
const [word, setWord] = useState(false);
return <Child propName={setWord}/>
}