Home > Software engineering >  JSX in fuction donot update state
JSX in fuction donot update state

Time:01-22

Can anyone give an answer?

Unable to update the state when I click getbtn -> placeRange pass jsx to setbtn ->then unable to update the State when Silde the Range.


import React, { useState } from "react";

export default function Stack() {
  const [value, setvalue] = useState(0);
  const [btn, setbtn] = useState(<></>);

  function placeRange() {
    const jsx = (
      <>
        <input
          type="range"
          onChange={(e) => {
            setvalue(e.target.value);
          }}
        />
        <h1>{value}</h1>
      </>
    );
    setbtn(jsx);
  }

  return (
    <>
      <button onClick={placeRange}>getrange</button>
      {btn}
    </>
  );
}

CodePudding user response:

This seems to be working for me.

Here's a working example at codesandbox

import { useState } from "react";

export default function App() {
  const [value, setvalue] = useState(0);
  const [btn, setbtn] = useState(<></>);

  function placeBtn() {
    const jsx = (
      <>
        <button
          onClick={() => {
            setvalue(1);
          }}
        >
          Convert to 1
        </button>
      </>
    );
    setbtn(jsx);
  }

  return (
    <>
      <h1>{value}</h1>
      <button onClick={placeBtn}>getbtn</button>
      {btn}
    </>
  );
}

CodePudding user response:

Not sure I fully understand what you are trying to achieve, this is not clear enough for me. From your code it seems you are trying to set an input range in place when clicking the button, then, you want this range to update the number below it.

If this is the case I suggest the following solution:

import React, { useState } from "react";

export default function Stack() {
  const [value, setvalue] = useState(0);
  const [showRange, setShowRange] = useState(false);

  function placeRange() {
    setShowRange(!showRange);
  }

  return (
    <>
      <button onClick={placeRange}>getrange</button>
      {showRange && (
        <>
          <input
            type="range"
            onChange={(e) => {
              setvalue(e.target.value);
            }}
          />
          <h1>{value}</h1>
        </>
      )}
    </>
  );
}
  •  Tags:  
  • Related