1

How can I get the user value in the text field component.

This is the form text field value I want to populate. I am using material ui and tried using hooks and useEffect to get the desired results.

<TextField variant="outlined" margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" autoFocus /> <FormControlLabel control={<Checkbox value="remember" color="primary" />} label="Remember me" /> <Button type="submit" fullWidth variant="contained" color="primary" className={classes.submit} onClick={handleClick} > Sign In </Button> </form> How can I get the password in alert/console log on handleClick. const handleClick = () => { console.log(password); }; 

1 Answer 1

3

You need to use State.
Whenever the value of the TextField change, you save the value in the component state. When you click submit, you have access to the state:

const TextFieldWithState = () => { const [password, setPassword] = useState(''); const handleClick = () => { console.log(password); }; return ( <form> <TextField variant="outlined" margin="normal" required fullWidth name="password" label="Password" type="password" id="password" autoComplete="current-password" autoFocus value={password} onChange={(event) => {setPassword(event.target.value)}} //whenever the text field change, you save the value in state /> <FormControlLabel control={<Checkbox value="remember" color="primary" />} label="Remember me" /> <Button type="submit" fullWidth variant="contained" color="primary" // className={classes.submit} onClick={handleClick} > Sign In </Button> </form> ); }; 

You can learn more about useState hook here

Sign up to request clarification or add additional context in comments.

5 Comments

How can I pass the value of password to other components ?@Ido Thanks
There are multiple ways. is 'other component' is a parent or sibling of the component in the question?
the details of the password needs to be transferred to a different page, handled using routing on handleClick method. So the password value needs to be sent to /view page. Thanks const handleClick = () => { history.push("/view"); };
In this case, you should use Redux library. It's a little difficult to catch at start- but it will pay off. It's a great way to share state between pages in your app. To get started, go through the Basic Tutorial
You can also Lift the state up to the first common ancestor of the two components (probably the component that renders <Route>). This is highly not recommended, beacuse as your app grows you will get into callback hell.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.