Here are the steps to convert the create-react-app
generated to code to use styled components instead of css
- Created an app using
create-react-app
create-react-app react-styledcomponents-app
- Install styled-components as a dependency
yarn add styled-components
- Replace the global styles in index.js
- Remove the line index.css import
import './index.css';
- Take a look at the App.js file
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
- We have 5 elements which can be converted to components
AppContainer -> The App wrapper AppHeader -> The Header section AppLogo -> Display of animated logo AppTitle -> Display of application title AppInto -> Paragraph for the introduction text
Create these 5 components now
const AppContainer = styled.div`
text-align: center;
`;
const AppHeader = styled.header`
background-color: #222;
height: 150px;
padding: 20px;
color: white;
`;
const AppTitle = styled.h1`
font-size: 1.5em;
`;
const AppLogo = styled.img`
animation: App-logo-spin infinite 20s linear;
height: 80px;
@keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
`;
const AppIntro = styled.p`
font-size: large;
`;
- Remove the App.css import from App.js and modify the App.js to include the newly created styled components
import { createGlobalStyle } from 'styled-components'
// Add global styles
const GlobalStyle = createGlobalStyle`
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
`
class App extends Component {
render() {
return (
<React.Fragment>
<GlobalStyle />
<AppContainer>
<AppHeader>
<AppLogo src={logo} alt="logo" />
<AppTitle>Welcome to React</AppTitle>
</AppHeader>
<AppIntro>
To get started, edit <code>src/App.js</code> and save to reload.
</AppIntro>
</AppContainer>
</React.Fragment>
);
}
}
Came across this - FYI
injectGlobal
has been deprecated as of v4