Search code examples
reactjstexttoggle

Toggle text within a variable type function in React JS


Let's say I have a function:

import React from "react";

const Test = () => {
  return (
    <React.Fragment>
      <h1>Hello World</h1>
    </React.Fragment>
  );
};

export default Test;

I want to toggle the Hello World text on and off with a button. How would I achieve this? I have looked at:

  1. How React.js Toggle Button Works

  2. React js onclick toggle class in map function

And none of them helped really. They used this.state, to which I got a type error, and then I started wondering if I should use a variable type function or not, as all the tutorials I've looked at use class instead. So my question is, how would I achieve toggling text in a variable type function?

If you need anymore information, or if my question was poorly phrased, please tell me. Any help is very much appreciated. Thank you!


Solution

  • this.state has no meaning in your functional component.

    Instead you could do something like this:

    import React, { useState } from "react";
    
    const Test = () => {
      const [showText, setShowText] = useState(false);
      return (
        <React.Fragment>
          {showText && <h1>Hello World</h1>}
          <button onClick={() => setShowText(!showText)}>Toggle</button>
        </React.Fragment>
      );
    };
    

    We use useState to create some state and set its initial value to false (i.e. The text should not be shown).

    Then inside the onClick property of our button we can toggle the state value between true and false by setting showText and use this to conditionally render the text.

    sandbox example