심시은
심시은

Reputation: 437

How can I set background image by dynamic names with styled-component?

I'm trying to set background-image with styled component. In the code below, I want to set background image with different divs, with img_01, img_02, img_03, .....

I saw many cases importing img path and use that, but I want to use dynamic name depending on the variable. Do I need to import all the images and set each of them?

import styled, { css } from 'styled-components';

const Div1 = styled.div`
        width: ${props => props.width};
        background: url('asset/images/img_0${props=>props.num}.png');
    `;

class Main extends Component {
    render() {
        return (
            <div>
                <Div1 width={"475px"} num={1}>

                </Div1>
                <Div1 width={"154px"} num={2}>

                </Div1>

            </div>
        )
    }
}

How Can I do that without importing all ?

Upvotes: 0

Views: 1231

Answers (1)

Deve
Deve

Reputation: 1779

You can write it like that :

const Div1 = styled.div`
    width: ${props => props.width};
    background-image: ${props => `url('asset/images/img_0${props.num}.png')`};
`;

Upvotes: 1

Related Questions