Maxime Ghéraille
Maxime Ghéraille

Reputation: 1905

setState not working inside onChange function

I am trying to found out why this works

const Navigation:React.FC = () =>{
    const [Volume, setVolume] = useState<number>(50)
    const onChange = (event) => {
        setVolume(event.target.value);
    }
    return(
        <>
            <Slider label="Slider label" value={Volume} onChange={(event) => onChange(event)} max='100' min='0'/>
        </>
    )

}

export default Navigation

But this does not work

const Navigation:React.FC = () =>{
    const [Volume, setVolume] = useState<number>(50)
    return(
        <>
            <Slider label="Slider label" value={Volume} onChange={(event: ChangeEvent<HTMLElement>)  => setVolume(event.target.value)} max='100' min='0'/>
        </>
    )

}

export default Navigation

It is giving this error Property 'value' does not exist on type 'EventTarget & HTMLElement'

I would like to use the second one because it makes my code a lot shorter and cleaner.

any idea why or how I could make the second one work

Thank for the help

Upvotes: 0

Views: 189

Answers (1)

Ivan V.
Ivan V.

Reputation: 8081

If I'm correct in assuming that this is a Typescript error, then you need the provide proper type for the event, there is no value property in the HTMLElement type, you need to use HTMLInputElement for the slider.

    const onChange = (event:React.ChangeEvent<HTMLInputElement>) => {
        setVolume(parseInt(event.target.value));
    }

Upvotes: 2

Related Questions