swirlm
swirlm

Reputation: 37

Dynamic background image with styled-components

I've been struggling with making this work, I have a prop called weather, it's value can be either Drizzle, Cloudy or any other type of Text.

I have images imported on the top (only two at the moment), I've tried with

background-image: url(${weather => (weather === 'Drizzle) ? Drizzle : Cloudy})

But it won't work, it will always go with Cloudy (false), I may need to make a nested ifs or ternary operators but at the moment I would like to get it working with two at least.

My code where I get the props destructured weather = 'Drizzle' would be the prop, for example)

import React from "react";
import styled from "styled-components";

import Drizzle from "../img/Drizzle.jpg";
import Cloudy from "../img/Cloudy.jpg";

const CardItems = styled.div`
  background-image: url(${Drizzle});


export default function Card({ max, min, name, img, onClose, weather }) {
  let icon = `http://openweathermap.org/img/wn/${img}@2x.png`;

  return (
    <CardItems>
      <TitleTwo>{name}</TitleTwo>
      <Image src={icon} alt="" />
      <TempsContainer>
        <TempText>
          <p>Min.</p>
          <p>{min}</p>
        </TempText>
        <TempText>
          <p>Max.</p>
          <p>{max}</p>
        </TempText>
      </TempsContainer>
    </CardItems>
  );
}

Upvotes: 1

Views: 886

Answers (1)

MB_
MB_

Reputation: 1747

Replace :

`background-image: url(${weather => (weather === 'Drizzle) ? Drizzle : Cloudy})`

by :

`background-image: ${(props) => props.current === 'Drizzle' ? `url(${Drizzle})` : `url(${Cloudy})`};`

App.js

import React from 'react';
import './App.css';

import Card from './Card';

export default function App() {
  return <Card weather="Drizzle" />;
}

Card.js

import React from 'react';
import styled from 'styled-components';

import Drizzle from './img/Drizzle.jpg';
import Cloudy from './img/Cloudy.jpg';

export default function Card({ weather }) {   
  return (
   <CardItems current={weather} />
  );
}

const CardItems = styled.div`
  height: 100vh;
  width: 100%;
  background-image: ${(props) =>
    props.current === 'Drizzle' ? `url(${Drizzle})` : `url(${Cloudy})`};
`;

Upvotes: 1

Related Questions