0

react useState hook won't update on input onChange event using react functional component

const [email, setEmail] = useState("");
// i'm not able to set input value in useeffect using this code
<GridItem xs={12} sm={12} md={4}>
  <CustomInput
    labelText="Email address"
    id="email-address"
    formControlProps={{
      fullWidth: true
    }}

    value={email}
    onChange={evt => setEmail(evt.target.value)}
  />
</GridItem>
sam
  • 1,767
  • 12
  • 15
CodeZoe
  • 3
  • 1
  • 5
  • 1
    What does the code (especially the ‘onChange’ part) of your ‘CustomInput’ look like? The code you provided here seems fine to me. Custom components don’t natively inherit eventListeners so my guess is that the problem is in that component instead – Luïs Oct 22 '19 at 05:27
  • Could you paste all the code of your `CustomInput` Component? – sam Oct 22 '19 at 05:28
  • I'm using material-ui theme and i want to store data using axios but useState don't set input value,here is my code – CodeZoe Oct 22 '19 at 05:32
  • @rinkal satasiya don't use onChange here. use inside CustomInput – akhtarvahid Oct 22 '19 at 05:32
  • @rinkalsatasiya check this example, hope it will help you https://stackoverflow.com/a/58497648/6544460 – akhtarvahid Oct 22 '19 at 05:34

3 Answers3

1

App.js

function App() {
  const [email, setEmail] = React.useState("");
  const handleChange = e => {
    setEmail(e.target.value);
  };
  return (
    <div>
      <h4>{email}</h4>
      <CustomInput handleChange={handleChange} />
    </div>
  );
}

CustomInput.js

import React from "react";

function CustomInput(props) {
  return (
    <div>
      <input type="text" onChange={props.handleChange} />
    </div>
  );
}

export default CustomInput;
akhtarvahid
  • 9,445
  • 2
  • 26
  • 29
0

Where is your function?

onChange={e => this.setEmail(e)} // use arrow function to bind this

setEmail = (e) => {
  yourSetFunction({[e.target.name]:e.target.value}) // assuming you give you input a name
}
tim
  • 677
  • 9
  • 11
0
const [email, setEmail] = useState(null);
const handleChange = (e) => {
  setEmail(e.target.value);
}
// i'm not able to set input value in useeffect using this code
<GridItem xs={12} sm={12} md={4}>
  <CustomInput
    labelText="Email address"
    id="email-address"
    formControlProps={{
      fullWidth: true
    }}

    value={email}
    onChange={handleChange}
  />
</GridItem>