get the value of a TextField component

54 views Asked by At

I have a component on react (with the help of materialui):

export default function AddToDo() {


    const classes = useStyles();
    return (
        <div style={{
            display: "flex"
        }}>
            <TextField className={classes.textField} label="Add todo"></TextField>
            <Button variant="contained" >Submit</Button>
        </div>
    )

}

basically it's a text box and a button. When the button is pressed, I want to call a method (that is declared above the code I showed) called addNew(param1). I want param1 to be the value that the user introduces inside the text field. How can I achieve this? Basically something like this:

<Button onclick=addNew(value inside the textfield) variant="contained" >Submit</Button>
1

There are 1 answers

0
Dennis On

You will need a state to store the value of the field and one callback to set the value:

const [text, setText] = React.useState("")

const fieldChangeHandler = React.useCallback((event) => setText(event.currentTarget.value))

And then add these properties to TextField component:

onChange={fieldChangeHandler}
value={text}

Then the value will be stored on text variable