Reputation: 842
I am using styled-components as a design library, I created a div that will hold a background image with its properties, if I inject the image url from outside the styled components it doesnt take and and does some mistakes.
Ill copy some code:
image-div component as styled component:
const ImageDiv = styled.div`
height: 100%;
width: 100%;
float: left;
background-repeat: no-repeat;
background-position: left;
background-size: cover;
`
export default ImageDiv;
using the ImageDiv on a screen and passing it a background image doesnt take the background properties from above
<ImageDiv style={{ backgroundImage: `url(${signin})` }} src = {signin} alt="logo" />
I will like to be able to pass the url as a prop and inject it into the styled component from above
Upvotes: 1
Views: 3048
Reputation: 1
You can use attrs
manipulator to change the attributes directly on the generated component. Through this, you can change several things, like buttons disabled-attribute or href for anchor tags, for example!
import styled from 'styled-components'
import { prop } from 'styled-tools'
export const ImageDiv = styled.div.attrs(({ url }: { url: string })`
height: 100%;
width: 100%;
float: left;
background-repeat: no-repeat;
background-position: left;
background-size: cover;
background-image: ${prop('url')};
`
Upvotes: 0
Reputation: 2468
Use destructuring props
const ImageDiv = styled.div`
height: 100%;
width: 100%;
float: left;
background-repeat: no-repeat;
background-position: left;
background-size: cover;
background-image: ${({url}) => `url(${url})`};
`
export default ImageDiv;
Upvotes: 0
Reputation: 41893
You could simply pass it as another prop, then use it inside styled component as background-image
property.
<ImageDiv bg={signin} src={signin} alt="logo" />
const ImageDiv = styled.div`
background-image: url(${(props) => props.bg});
`;
Upvotes: 4