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.
2
Answers
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:
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.
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.
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.