Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to style child components in react styled-components

I'm trying to style the child component of a styled-component, but it sends the css to the parent instead of the child/ This is my code,

export const Card = styled.div`
  position: relative;
  ${props => props.horizontal && `
  ${CardImage}{
     max-height: 60%;
     overflow: hidden;
  }`}
`
export const CardImage = styled.div`
    position: relative;
`

EDIT: When I add a condition before rendering that's when it doesn't work

like image 270
Marvin Avatar asked Apr 02 '18 22:04

Marvin


People also ask

How do you style a child component in React?

Use React API cloneElement() type, props, children) , so basically we can't change anything of it. By cloneElement() , we can recreate the children with new props. To change the style, we can pass in a style prop into the image and also we can add an onClick handler to change the gallery state.

Can you add style to React component?

There are four different options to style React components. All depend on your personal preferences and the specific complexity of your application. If you want to add just a few style properties, then inline styling is the best option.


1 Answers

You're almost there, you're just missing a $ in your code and you'll need to move the CardImage above the Card component:

export const CardImage = styled.div`
    position: relative;
`

export const Card = styled.div`
    position: relative;
    ${CardImage}{
        max-height: 60%;
        overflow: hidden;
    }
`

Edit (04/04/2018):

If you want to add a condition around a whole block like you have, you need to import the css function from styled components and use that:

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

export const CardImage = styled.div`
    position: relative;
`

export const Card = styled.div`
    position: relative;

    ${props => props.horizontal && css` // - Notice the css` here.
        ${CardImage}{
            max-height: 60%;
            overflow: hidden;
        }
    `}
`
like image 90
Cubed Eye Avatar answered Oct 15 '22 19:10

Cubed Eye