Reputation:
I have the folder structure like the following.
src/
components/
Icon/
Icon.js
Style.js
images/
apple.svg
google.svg
facebook.svg
index.js
I want to export the paths of images under images folder in 'images/index.js'.
I tried something like this below.
export const apple = './apple.svg';
export { google } from './google.svg';
export const facebook = './facebook.svg';
And I want to load the paths of those images in '/Components/Icon/Style.js' like the following.
import styled from 'styled-components';
// I know this works fine
import apple from '../../images/apple.svg';
// This doesn't work although I want it to work.
import { google } from '../../images/index';
// This doesn't work as well although I want it to work.
import { facebook } from '../../images/index';
const Icon = styled.i`
background: blah blah blah
`;
export default Icon;
However, I couldn't load the paths of images.
What is the right way to do that?
Is it impossible?
export const apple = './apple.svg';
Is this the only way I can load the path of image?
Upvotes: 2
Views: 2015
Reputation: 4080
import apple from './apple.svg';
import google from './google.svg';
import facebook from './facebook.svg';
export {
apple,
google,
facebook
}
import styled from 'styled-components';
import { apple, google, facebook } from '../../images';
const Icon = styled.i`
background: blah blah blah
`;
export default Icon;
Requesting an image for every "icon" to your server feels really expensive. Instead, since you have access to the resources I would go with this structure:
src/
components/
Icon/
Apple.js
Google.js
Facebook.js
import React from 'react';
function Facebook({ width = '266', height = '266' } = {}) {
return (
<svg xmlns="http://www.w3.org/2000/svg" width={width} height={height} viewBox="0 0 266.893 266.895" enableBackground="new 0 0 266.893 266.895">
<path
fill="#3C5A99"
d="M248.082,262.307c7.854,0,14.223-6.369,14.223-14.225V18.812 c0-7.857-6.368-14.224-14.223-14.224H18.812c-7.857,0-14.224,6.367-14.224,14.224v229.27c0,7.855,6.366,14.225,14.224,14.225 H248.082z"
/>
<path
fill="#FFFFFF"
d="M182.409,262.307v-99.803h33.499l5.016-38.895h-38.515V98.777c0-11.261,3.127-18.935,19.275-18.935 l20.596-0.009V45.045c-3.562-0.474-15.788-1.533-30.012-1.533c-29.695,0-50.025,18.126-50.025,51.413v28.684h-33.585v38.895h33.585 v99.803H182.409z"
/>
</svg>
);
}
export default Facebook;
Advantages:
Upvotes: 1