jan
jan

Reputation: 255

How do i make a very basic useState hook in React?

I'm trying to make a very basic useState hook in React, but cant figure out what im doing wrong. This is a simple useState that changes the text inside the paragraph to whatever you write in the textfield.

export default function Demo() {

const [value, setValue] = React.useState();
const handleValue= () => {
    setValue(value)
}
  
return(

  <>
    <TextField onChange={handleValue} />
    <p>{value}</p>
  </>

 )
}

The paragraph doesn't render anything. Did I miss something?

Upvotes: 1

Views: 45

Answers (2)

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4557

Your handleChange function is currently setting the value to itself. You must assign it to the value obtained from the TextField.

Here is a working example.

const {
  useState,
  useEffect,
  Fragment
} = React;

function Demo() {
  const [value, setValue] = useState();
  const handleValue = ({target}) => {
    setValue(target.value);
  }
  
  return <Fragment>
      <input type="text" onChange={handleValue}/>
      <p>{value}</p>
    </Fragment>;
}

const el = document.querySelector("#root");
ReactDOM.render(<Demo/>, el);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.6/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.6/umd/react-dom.production.min.js"></script>

<div id="root"></div>

Upvotes: 1

JuanCaicedo
JuanCaicedo

Reputation: 3418

You'd need to handle the value coming out of the change handler and use it to update your state 😀

export default function Demo() {

const [value, setValue] = React.useState();
const handleValue= (e) => {
    setValue(e.target.value)
}
  
return(

  <>
    <TextField onChange={handleValue} />
    <p>{value}</p>
  </>

 )
}

Upvotes: 0

Related Questions