1import React from 'react'
2import logo from './logo.svg' // Tell Webpack this JS file uses this svg
3
4console.log(logo) // /logo.84287d09.svg
5
6function Header() {
7 // Import result is the URL of your image
8 return <img src={logo} alt="Logo" />
9}
10
11export default Header
You can import an SVG as a React Component. This has been supported since Create React App 2.0 (react-scripts@2.0.0
and react@16.3.0
)
1import { ReactComponent as MyIcon } from './icon.svg'
2export { MyIcon }
1import { ReactComponent as Logo } from './logo.svg'
2const App = () => (
3 <div>
4 {/* Logo is an actual React component */}
5 <Logo className="App-logo" alt="logo" />
6 </div>
7)
Don’t forget the curly braces in the import! The ReactComponent import name is special and tells Create React App that you want a React component that renders an SVG, rather than its filename.
A ReactComponent
SVG will show as inline <svg>
when rendered. You can now use all the CSS magic.
1.App-logo g {
2 fill: red;
3}
4
5.App-logo path {
6 stroke: palegoldenrod;
7 stroke-width: 10px;
8 fill: none;
9 stroke-dasharray: 35px 15px;
10 animation: orbit 1s infinite linear;
11}
12
13@keyframes orbit {
14 to {
15 sroke-dashoffset: 50px;
16 }
17}
To be continued.. Will probably have to leave the .svg
files and add the paths in a .jsx
file so we could use props
Case for converting SVGs into React components
1// wrapping SVGs in theme-able components
2import styled from 'styled-components';
3import theme from 'styled-theming';
4
5export const backgroundColor = theme('mode', {
6 light: '#fafafa',
7 dark: '#0e0f11'
8});
9const LogoWrapper = styled.div`
10 svg {
11 fill: ${backgroundColor};
12 }
13`;