Reputation: 31
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;
}
Upvotes: 1
Views: 442
Reputation: 5838
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;
Upvotes: 2