Home > Software design >  Why input value does not change when we pass null or undefined as a value?
Why input value does not change when we pass null or undefined as a value?

Time:11-11

While working with the controlled input components if we set the value of the controlled component to null or undefined the previous value is still displayed on the UI instead of changing it and the state holding that input value changes to null or undefined. I have created a sandbox for better understanding

https://codesandbox.io/s/black-architecture-0wqw1

Thank you

CodePudding user response:

If the data type is null or undefined react automatically supress that value and log nothing.

If you want to see the type of that particular value, write {typeof data}, then you'll get your answer.

...
setData(null)
typeof data // object

setData("hi")
typeof data // string

setData(undefined)
typeof data // undefined
...

CodePudding user response:

here is quick fix, it never changes value variable, if data then put data else empty string, that how it works

<input
    type="text"
    onChange={(e) => setData(e.target.value)}
    value={data ? data:""}
  />

i hope this will solve your problem, here is complete fix, https://codesandbox.io/embed/optimistic-currying-snn8t?fontsize=14&hidenavigation=1&theme=dark

CodePudding user response:

You can use ref tout change the value of your input anywhere outside your input component, see bellow :

import React, { useState, useEffect } from "react";
import "./styles.css";

export default function App() {
  const [data, setData] = useState(null);
  const inputRef = React.useRef(null);
  useEffect(() => {
    console.log(data);
  }, [data]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <input
      ref={inputRef}
        type="text"
        onChange={(e) => setData(e.target.value)}
        value={data}
      />
      <div style={{ marginTop: "10px" }}>
        <button onClick={() => {
          setData(null);
          inputRef.current.value = ''
          }}>SET DATA NULL</button>
      </div>
      <div style={{ marginTop: "10px" }}>
        <button onClick={() => {
          setData(undefined)
          inputRef.current.value = ''
          }}>
          SET DATA UNDEFINED
        </button>
      </div>
      <div style={{ marginTop: "10px" }}>INPUT VALUE {data}</div>
    </div>
  );
}
  • Related