Reputation: 25
I've tried everything. At least, for a while, I can't find any new possible solution for my problem. There is a possibility that I don't understand something, because I'm at the beginning of my adventure with React.js.
To the point:
I want to create a component-header with a background image. In the parent component, I put an image URL as a prop and try to use it in the child component as a background-image: URL()
. And it, of course, doesn't work. Also, I've tried to set a colour, and it also doesn't work.
Here is my parent component:
import Hero from '../Hero';
import image from './cat.jpg'
function Main() {
return <div>
<Hero title="Only fluff photos" image={image} color="#f0f"/>
</div>
};
and here is my child component:
import styled from 'styled-components';
const StyledHeader = styled.header`
display: flex;
width: 100%;
height: 432px;
background-image: url(${(props) => props.image});
background-color: ${props => props.color ? props.color : "#ff0"};
`
function Hero(props) {
return <StyledHeader>
<h1>{props.title}</h1>
<img src={props.image} alt="test cat" />
</StyledHeader>
};
What I've tried:
src
- it works{image}
- it worksrequire()
- it doesn't workurl(~{props.image})
- it doesn't workStyledHeader
- it doesn't workOf course, all of points from 3 to 6 doesn't work, because none of props works. But I've found that later.
styled-components gives an example of props usage:
background: ${props => props.primary ? "palevioletred" : "white"};
It doesn't help me :(
Thanks in advance for any help! I have no idea what I've done wrong.
Upvotes: 1
Views: 3505
Reputation: 254
It won't work because you have to give the Styled header the prop as followed
const StyledHeader = styled.header`
display: flex;
width: 100%;
height: 432px;
background-image: url(${(props) => props.image});
background-color: ${props => props.color ? props.color : "#ff0"};
`
function Hero(props) {
return <StyledHeader image={props.image} color={"value"} {...otherProps}>
<h1>{props.title}</h1>
<img src={props.image} alt="test cat" />
</StyledHeader>
};
Upvotes: 4