1

How can i apply my css code as styled-component in app.js ? How can i convert this ".container > div" into styled-component and use it in my app.js . After installing styled-component through npm install then importing it. I am stuck here . I am not able to apply some css style in styled-components.

App.js

 import React, { Component } from 'react';
 import './App.css';

 class App extends Component{
  render(){
    return (

      <div class="container">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
      </div>
           );
         }
       }

 export default App;

App.css

.container
 {
   display: grid;
   grid-template-columns: auto auto auto;
   grid-template-rows: 50px 50px;
 }

.container > div 
 {
   display: flex;
   justify-content: center;
   align-items: center;
   font-size: 2em;
   color: #ffeead;
 }

html, body 
 {
 background-color: #ffeead;
 margin: 10px;
 }

.container > div:nth-child(1n)
 {
  background-color: #96ceb4;    
 }

.container > div:nth-child(3n) 
 {
  background-color: #88d8b0;
 }

.container > div:nth-child(2n)
 {
   background-color: #ff6f69;
 }

.container > div:nth-child(4n)
 {
   background-color: #ffcc5c;
 }

1 Answer 1

2

Create a component based on a div that serves as container and write down your CSS. The trick here is to apply the appropiate style to the children div of the component Container, you need to use & (represents the parent selector) inside the template literal to create the needed nestings so SC can generate the appropiate CSS classes.

import React, { Component } from 'react';
import styled from 'styled-components';
import './App.css';

const Container = styled.div`
  display: grid;
  grid-template-columns: auto auto auto;
  grid-template-rows: 50px 50px;

  & > div {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 2em;
    color: #ffeead;
  }

  & > div:nth-child(1n) {
    background-color: #96ceb4;    
  }

  & > div:nth-child(3n) {
    background-color: #88d8b0;
  }

  & > div:nth-child(2n) {
    background-color: #ff6f69;
  }

  & > div:nth-child(4n) {
    background-color: #ffcc5c;
  }
`;


class App extends Component{
  render(){
    return (
      <Container>
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
        <div>5</div>
        <div>6</div>
      </Container>
    );
  }
}

export default App;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.