Home > front end >  Is it possible to use css transition in React?
Is it possible to use css transition in React?

Time:01-13

For example I have this code. And I want to use CSS transitionfor Button when showButton and when !showButton. Now it's just removed and add Button when showButton changes.

{showButton && (
        <Button
          onClick={() => setShowMessage(true)}
          size="lg"
        >
          Show Message
        </Button>
      )}

Is it possible make by some events or appending classNames like active?

CodePudding user response:

Append the className with the ternary operator.

But, for example, this code will only adjust the class of the button specified (effectively doing the same thing you described, hiding & showing the button):

import React, { useState } from 'react';

export const Component = () => {
    const [showButton, setShowButton] = useState(false);

    const handleClick = () => {
        setShowButton(true);
    }

    return (
        <button
            onClick={handleClick}
            className={showButton ? 'showButtonClass' : 'hideButtonClass'}
        >
            Show Message
        </button>
    );
};

For content to show once the button is clicked, you'll need something like:

import React, { useState } from 'react';

export const Component = () => {
    const [showMessage, setShowMessage] = useState(false);

    const handleClick = () => {
        setShowMessage(true);
    }

    return (
        <div>
            <button
                onClick={handleClick}
            >
                Show Message
            </button>
            {showMessage && <h1>
                The message you'll see when clicking!
            </h1>}
        </div>
    );
};
  • Related