Wordpressor
Wordpressor

Reputation: 7543

How to use inline styles with styled-components in React?

I've a fairly simple React component:

import styled from 'styled-components';
import { formatUrl } from "formatUrl";

const StyledWrapper = styled.div`
  padding: 20px;
`;

const StyledImage = styled.img`
  border: solid 5px green;
`;


const MyComponent = ({ data }) => {
  const url = formatUrl(data.foo.url);

  return (
    <StyledWrapper>
     <StyledImage></StyledImage>
    </StyledWrapper>
  );
};


export default MyComponent;

But I have absolutely no idea how to set <StyledImage> to have background-image with url({url}). The URL is getting formatted within MyComponent and I can't really access it outside of the component. How should I proceed in this case? Is there a generic solution to this?

I want do do something like this:

<StyledImage styles="background-image: url({url})"></StyledImage>

I know I could use "props" where describing styles for StyledImage, yet I'm not sure if it's a good idea to format data there, this won't scale well

Note: I'm planning on moving my styled components to separate file in the future so StyledWrapper and StyledImage will be imported (not sure if it changes anything).

Thanks for any hints.

Upvotes: 2

Views: 8525

Answers (2)

Fegig
Fegig

Reputation: 51

This should work easily.

import styled from 'styled-components';
import { formatUrl } from "formatUrl";

const StyledWrapper = styled.div`
  padding: 20px;
`;

const StyledImage = styled.div`
background-image: url("${props => props.imageUrl}") center center no-repeat
  border: solid 5px green;
`;


const MyComponent = ({ data }) => {
  const url = formatUrl(data.foo.url);

  return (
    <StyledWrapper>
     <StyledImage imageUrl={url}/>
    </StyledWrapper>
  );
};


export default MyComponent;

Upvotes: 1

Imran Rafiq Rather
Imran Rafiq Rather

Reputation: 8078

I have come up with the following solution general solution, which is working fine for me. I created the following Image.js component:

 import styled from "styled-components";

 const url = "https://picsum.photos/200/300";

const Image = styled.img.attrs({
  src: `${url}`,
})``;

export default Image;

Imported the Image Component in my App.js and used as <Image /> it worked fine.

In your case you should make following changes to make it work:

const MyComponent = ({ data }) => {
  const url = formatUrl(data.foo.url);
  // Create Image Component here as you are getting url from data props
   const StyledImage= styled.img.attrs({
    src: `${url}`,
  })`border: solid 5px green;`;

  return (
    <StyledWrapper>
      <StyledImage/>
    </StyledWrapper>
  );
};

Upvotes: 1

Related Questions