Ysm
Ysm

Reputation: 25

Styled-components in React.js - props doesn't work

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:

  1. Put the same URL into img tag as a src - it works
  2. Import an img directly in child component and us {image} - it works
  3. Use require() - it doesn't work
  4. Use url(~{props.image}) - it doesn't work
  5. Use different forms of props when styling my StyledHeader - it doesn't work
  6. Put an image into a folder that has exactly the same path for both components - it doesn't work.

Of 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

Answers (1)

Slavian
Slavian

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

Related Questions