pi2018
pi2018

Reputation: 357

How to use Styled Components to add className to an existing component

I have learned the basics of how to use JSS using Material-ui's {withStyle} property. I just came across 'styled-components' and I am trying to learn the basics of it. But I am unable to find the documentation regarding how to create "classNames" with styled-components. Please have a look at the code snippet below for what I am trying to do with JSS and can you please help me how with the styled-component part

// WITH JSS======

import React, { Component } from 'react';
import { withStyles } from '@material-ui/core';

const myStyle = {
  container : {
      backgroundColor : "blue"
  }
}

function MySampleComponent = ({classes}) => {
     return(<div>
              <div className={classes.container}> This one is styled 
              </div>
              <div> This one is not </div>
            </div>
        )
}

export default MySampleComponent;


//Now with 'Styled-Components'. 
//I know how to create a .div element with the given styles but I don't know how to name them so that I can use that variable to assign a className for only one of the divs.

const myStyledDiv = styled.div` background-color : blue; `

How do I use the variable name 'myStyledDiv' and assign it to the first div in the example.

Upvotes: 1

Views: 4297

Answers (1)

Ido
Ido

Reputation: 5758

Styled components has a different approach.
You shouldn't look at myStyledDiv as a variable, look at it as a component with custom styles.
From styled-components docs:

styled-components removes the mapping between components and styles. This means that when you're defining your styles, you're actually creating a normal React component, that has your styles attached to it.

Therefore, when using styled-components, you don't declare 'myStyledDiv' variable and assign it to div classname.
You create a 'MyStyledDiv' component (which is a div with custom styles), and use it that way:

import styled from 'styled-components'

const MyStyledDiv = styled.div`
    background-color: blue;
`;

function MySampleComponent = (props) => {
     return(<div>
              <MyStyledDiv> 
                 This one is styled 
              </MyStyledDiv>
              <div>
                 This one is not 
              </div>
            </div>
        )
}

Upvotes: 3

Related Questions