Home > database >  How to swap svg in React using a function?
How to swap svg in React using a function?

Time:08-11

I want to swap svg images. How to do it?

I add them to the React app:

import { ReactComponent as Paint } from '../style/ImagesGame/PaintBrush.svg';
import { ReactComponent as MagicWand } from '../style/ImagesGame/MagicWand.svg';

<Pain/>
<MagicWand/>

Please help me to swap pictures using the function

CodePudding user response:

Use conditional rendering to switch between which SVG is displayed:

import { ReactComponent as Paint } from '../style/ImagesGame/PaintBrush.svg';
import { ReactComponent as MagicWand } from '../style/ImagesGame/MagicWand.svg';

const Foo = () => {
  const [paintMode, setPaintMode] = useState(true);

  return (
    <div>
      <div>
        {paintMode ? (
          <Paint />
        ) : (
          <MagicWand/>
        )}
      </div>
      <button type="button" onClick={() => setPaintMode((curr) => !curr)}>Toggle Mode</button>
    </div>
  );
};
  • Related