score:1

Accepted answer

do not store html node inside state. you can simply store only a boolean value to switch between what node to show. i'm not pretty sure but it may cause weird behavior since react internally depends heavily on the dom/html ui tree (see managing state).

try this instead:

import { usestate } from "react";
import "./styles.css";

function app() {
  const [inputval, setinputval] = usestate("");  // initialize as empty string.
  const [showdiv, setshowdiv] = usestate(false);

  const changedivfunc = () => {
    setshowdiv(true);
  };

  const getinputval = (event) => {  // the arg is event object, not val
    setinputval(event.target.value);
  };

  const alertval = () => {
    alert(inputval);
  };

  return (
    <div classname="app">
      <h1>example</h1>
      <br />
      <button onclick={changedivfunc}>change div</button>
      {
        showdiv? (
          <div>
            <p style={{ color: "red" }}>
               hello world. this is updated "show div" value
            </p>
            <input value={inputval} onchange={getinputval} type="text" />
            <br />
            <br />
            <button onclick={alertval}>show input value</button>
          </div>
        ) : (
          <div>
            <p>hello world. this is default "show div" value</p>
          </div>
        )
      }
    </div>
  );
}

export default app;

forked codepen


Related Query

More Query from same tag