DEV Community

Cover image for Working with Styled Components in ReactJS
Anietie Brownson
Anietie Brownson

Posted on

Working with Styled Components in ReactJS

Does anyone know how to style images using Styled Components in React?
I can't seem to find a solution anywhere

Oldest comments (7)

Collapse
 
mykezero profile image
Mykezero • Edited

I'm absolutely terrible with CSS, but maybe something like this will work?
codepen.io/Mykezero/pen/jOaajZK

You can also place the styled component in a separate file and export it to share the style as well. Hopefully this helps! ^^

Collapse
 
mrpaulishaili profile image
Paul C. Ishaili

First, you can style your component, using a specified class, in a css file, and import the file into your the App.js file. That can work too.

Collapse
 
ramisj12 profile image
Rami S. Jaber

i am java developer for 10 years and just 2 years ago i learned css haha

Collapse
 
link2twenty profile image
Andrew Bone

What are you trying to achieve?

const Image = styled.img`
  border-radius: 6px;
`

<Image src="image/location.gif" alt="some gif" />
Enter fullscreen mode Exit fullscreen mode

Something like this is how you'd make a styled img tag.

Collapse
 
ageekdev profile image
ΛGΣΣK

Styled-components just helps you write CSS in JS. It's not a component library, better find a React/JavaScript component that handle images properly (lazy loading, placeholder, caching, responsive, multiple sizes, etc). next/image or lazysizes are good start. Then wrap that image component with style-components to play well with your codebase.

Collapse
 
mrpaulishaili profile image
Paul C. Ishaili

First, you can style your component, using a specified class, in a scss / css file, and import the file into your the App.js file. That can work too.

Collapse
 
anni profile image
Anietie Brownson

Thank you all for your suggestions. I figured out a way of doing it without using CSS

I wrapped the image in a div:

export const PrimaryImage = styled.div`
width: 80%;

Then I specifically targeted the image like this:

& > img {
width: 100%;
height: max-content;
border-radius: 15px;
}
`;

I did this in an image.elements.js file and then imported it in my main JS file

Problem solved!