Home > Net >  value of TextField input from event target in react with typescript
value of TextField input from event target in react with typescript

Time:04-09

I'm trying to console log the value of the TextField input in material ui while using typescript in react. But I got undefined in the console. I tried several solutions, but none worked.

Here's my code:

const HomePage: React.FC = () => {

    const onSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        console.log((e.currentTarget as HTMLInputElement).value);
    };

    return (
        <Container maxWidth="xl">
            <div style={{width: '385px', margin: 'auto'}}>
                <form onSubmit={(e) => {onSubmit(e)}}>
                    <Stack direction='row' spacing={1}>
                        <CustomTextField placeholder="Enter name" label="Name" type="text" variant="outlined" name="name" />
                        <Button type="submit" variant="contained" size='large'>Add</Button>
                    </Stack>
                </form>
            </div>
        </Container>
    )
}

export default HomePage;

CodePudding user response:

I think you may have conflated two examples on dealing with input values to get an incorrect solution.

Because the onSubmit handler is attached to the form, it will have access to all the input values within that form within event.target.elements[..].value, of which there could be many. You can then select the value you want using the name attribute of the input, in this case you have set it to name="name" so your onSubmit handler can access it as such:

    const onSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        console.log(e.target.elements.name.value);
    };

Edit: you could also access the input directly by dropping the .elements, so e.target.name.value would also work.


What I think you may have confused this with is an onChange handler attached to an input, such as <CustomTextField />, where because there is only one input the event object is able to hold the value at event.target.value.

CodePudding user response:

I managed to get the value by using the following:

const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        const name = (e.currentTarget.elements.namedItem('name') as HTMLInputElement).value;
    };
  • Related