Home > Software design >  React onclick change variable/state to return different html
React onclick change variable/state to return different html

Time:05-07

I am trying to have html be rendered while x =true, and different html while x = false. I am not sure how to do this in react but I thought of two ways, both which do not work. Way one:

function App() {

  var x = true

  function switchX() {
    x = false;
    window.location.reload()
  }

  return (
    <div className="App">
      {x ? <h1>hello</h1> : <h1>Goodbye</h1>}
      <button onClick={switchX}>Swap</button>
    </div>
  );
}

And way 2, using state:

function App() {
  const [x, setx] = useState(
    {
      x: true
    }
  )


  function switchX() {
    setx({x : false})
    window.location.reload()
  }

  return (
    <div className="App">
      {x ? <h1>hello</h1> : <h1>Goodbye</h1>}
      <button onClick={switchX}>Swap</button>
    </div>
  );
}

CodePudding user response:

You're nearly there.. try not to think too much of state having to be an object like it was in class components... hooks allow you to abstract each variable and control each individual state.

const myComponent = () => {
   const [x, setX] = useState(false);

   return (
      <>
         { x ? <div>x is true</div> : <div>x is false</div> }
         <button type='button' onClick={() => { setX(!x); }}
      </>
   );

}

CodePudding user response:

Below is the correct way of getting the value out of your state. State from hooks is not named. useState returns the state value without any transformations. Note that const [y, setX] = useState({x:false}) would still compile because you're just declaring a variable called y.

function App() {
  const [{ x }, setx] = useState(
    {
      x: true
    }
  )
  ...

CodePudding user response:

If you use function based component you should use useState hook. On handleChange method just toggle the current state value.

import { useState } from 'react';

const myComponent = () => {
const [x, setX] = useState(false);

const handleChange=()=>setX(!x)

return (
   <>
     { x ? <div>x is true</div> : <div>x is false</div> }
     <button  type='button' 
      onClick={handleChange}>Change</button>
   </>
 );
}
export default myComponent
  • Related