skip to Main Content

My Slide component with svg picture is not working. It’s just showing a white box moving from left to right, (with no actual picture). How can I get this to work?

Following the documentation here: https://mui.com/material-ui/transitions/

import { Paper, Slide } from '@material-ui/core';
import OfficeWorker from './OfficeWorker.svg';

const TestButtons = () => {
  const [buyButtonClicked, setBuyButtonClicked] = useState(false);

  const onBuyNow = () => {
    setBuyButtonClicked(true);
  };

  const OfficeWorkerIcon = (
    <Paper elevation={4}>
      <Box component="svg">
        <img src={OfficeWorker} />
      </Box>
    </Paper>
  );

  return (
    <Box>
      <Box marginRight={3}>
        <Button onClick={onBuyNow}>
          Buy it now
        </Button>
        <Button display="flex">Questions? Give us a call!</Button>
      </Box>

      <Slide direction="right" in={buyButtonClicked} mountOnEnter unmountOnExit>
        {OfficeWorkerIcon}
      </Slide>
    </Box>
  );
};

export default TestButtons;

Only a WhiteBox shows from Left to Right.

enter image description here

2

Answers


  1. You can’t just use svg files out of the box in React like you are. What I recommend you do is go to https://react-svgr.com/playground/. This is a nice tool that converts an SVG into a react friendly component.

    You can take the contents of svg file and paste it into that site like so:

    enter image description here

    Then copy the JSX Output. Use it to create a component in your application. Import and use that component in your Slide animation. NOTE: I couldn’t get it work placing the svg component directly inside of the Slide component. I had to use a Box.

    <Slide direction="right" in={buyButtonClicked} mountOnEnter unmountOnExit>
      <Box>
        <SvgComponent />
      </Box>
    </Slide>;
    

    That’s the easiest way. If you want to do a deeper dive, check out this article which goes over how to change webpack configuration file to allow using svg files in React.

    Login or Signup to reply.
  2. You can use MUI’s SvgIcon component, available at: https://mui.com/material-ui/api/svg-icon/

    Just place your SVG icon inside the tag and the slider will work as expected.

    import { SvgIcon, Slide, Box } from '@mui/material';
    import { TbSquareRoundedNumber1Filled } from 'react-icons/tb'
    
    <Slide direction="right" in={buyButtonClicked} mountOnEnter unmountOnExit>
      <Box>
        <SvgIcon style={{ fontSize: "80px" }} inheritViewBox >
          // your icon tag or path...
          // example: <TbSquareRoundedNumber1Filled color='#77b142' />
        </SvgIcon>
      </Box>
    </Slide>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search