2

I have the following code:

// @flow
import React from 'react';
import { Route } from 'react-router-dom';
import Split from '../../components/grouping/Split';
import CenterBox from '../../components/grouping/CenterBox';
import styled from 'styled-components';

type Props = {
  routes: Array<Object>,
  background: String
};


export default ({ routes, background }: Props) =>
  (<div>
    <Split push="right" alignItems="center" height={50} pad={{ horizontal: 20 }}>
      <div />
      <div>This feature will be available soon!</div>
    </Split>
    <DashboardContent background={background}>
      <CenterBox>
        <div style={{ transform: 'translateY(50%)' }}>
          <CenterBox height={300} width={500} backgroundColor="#FFFFFF">
            This feature is not included as part of the design beta and will be available soon
          </CenterBox>
        </div>
      </CenterBox>
    </DashboardContent>
  </div>);



  const DashboardContent = styled.div`
  background: url(${props => props.background}) no-repeat top
      center;
    background-size: 100%;
    min-height: 100vh;
  `;

I would like to pass background as a prop to my styled component so that when it is passed a link to an image file it sets it as a background, the code compiles but the background does not show up. What am I doing wrong?

snowflakekiller
  • 3,428
  • 6
  • 27
  • 45

3 Answers3

9

Changing your background property to be a function that returns a string will fix your issue.

background: ${props => `url(${props.background}) no-repeat top center`};
Ben Derham
  • 91
  • 1
  • 3
  • I didn't even need to use an arrow function to pass props as backgroud image. I just did ```background: url(${props.bgImage1}), url(${props.bgImage2}) center no-repeat``` and it worked fine. I'm using react 18.2.0 and styled-components 5.3.6. – tem Jan 10 '23 at 12:54
1

Is this going to work out fine?

 const DashboardContent = styled.div`
  background: url(${props => props.background}) no-repeat top center;
 `

 <DashboardContent background={`https://xxxx/xxxx${background}`}/>
heyfranksmile
  • 169
  • 1
  • 5
0

This worked for me!

import styled from 'styled-components';
import img from './img/background.gif';
        
const Content = styled.div`
    background-image: url(${img});
`;
kelsny
  • 23,009
  • 3
  • 19
  • 48
Pedro Leite
  • 21
  • 1
  • 6