Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to swap svg in React using a function?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
  );
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading