<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ styled-components - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ styled-components - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 27 Jun 2026 20:02:55 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/styled-components/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use Styled Components in Your React Apps ]]>
                </title>
                <description>
                    <![CDATA[ Styled-components is a library that allows you to write CSS in JS while building custom components in Reactjs. There are multiple options you can go with to style a React application. But the CSS in JS technique is good approach, where you write the ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/styled-components-in-react/</link>
                <guid isPermaLink="false">66d45f74ffe6b1f641b5fa0f</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ styled-components ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Thu, 04 May 2023 14:19:57 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/05/Frame-390.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Styled-components is a library that allows you to write <code>CSS in JS</code> while building custom components in <code>Reactjs</code>.</p>
<p>There are multiple options you can go with to style a React application. But the <code>CSS in JS</code> technique is good approach, where you write the <code>CSS</code> code right in the <code>JavaScript file</code>. Styled-components takes this approach.</p>
<p>In this article, you will learn how to write CSS in JS.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before we go ahead with styled components, you should be familiar with <code>React</code> and <code>CSS</code>.</p>
<h2 id="heading-how-to-create-a-basic-react-app">How to Create a Basic React App</h2>
<p>Before getting started with styled components, let's start by creating a React app using <code>create-react-app</code> .</p>
<pre><code class="lang-javascript">npx create-react-app APP_NAME
</code></pre>
<p>If you are not familiar with create-react-app, you can <a target="_blank" href="https://reactjs.org/docs/create-a-new-react-app.html">check here</a> for more information.</p>
<p>Once you React boiler plate is set, remove all files from <code>src</code> folder except <code>index.js</code> and <code>app.js</code>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/ss1-2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>This is how your files should look like when you are done with the above steps. Now it's time to clean up <code>app.js</code> and <code>index.js</code>. Now index.js and app.js will have some default boiler code. We need to remove unnecessary stuff from these files. After removing unnecessary stuff you app.js and index.js should look like code below in respective files.</p>
<p><code>App.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span>(
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            App
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    )
}
</code></pre>
<p><code>index.js</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>

<span class="hljs-keyword">const</span> root = ReactDom.createRoot(<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>))
root.render(
    <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
)
</code></pre>
<p>Now open the command line or press ctrl + <code>(backtick) to open it and type</code>npm start` to start your React app.</p>
<p>Once your app is running successfully, stop your server using ctrl + c and install styled-components. The command to install styled-components is below:</p>
<pre><code class="lang-javascript">npm install styled-components
</code></pre>
<h2 id="heading-lets-style-our-first-component">Let's Style Our First Component</h2>
<p>We will create a basic setup to help you learn styled components. In app.js, create a heading using an</p>
<h1 id="heading-tag-a-paragraph-using-a-tag-and-a-button-using-the-tagappjs-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-export-default-appbefore-we-style-our-component-we-need-to-import-styled-components-into-our-appjs-fileimport-styled-from-styled-components-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-export-default-appnow-we-will-create-our-custom-component-called-h1-and-use-it-instead-of-the-tag-with-custom-styling-const-h1-styledh1-color-red-font-size-4rem-first-we-need-give-a-custom-name-of-our-choice-then-well-start-with-styled-and-wrap-the-style-in-backticks-now-when-we-use-this-custom-component-it-will-have-the-property-with-stylingimport-styled-from-styled-components-const-h1-styledh1-color-red-font-size-4rem-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-export-default-appvoila-here-we-have-our-first-custom-styled-componentnote-always-use-uppercase-letters-to-start-your-custom-component-name-in-react-as-it-is-react-conventionnow-if-you-inspect-the-page-you-will-see-some-gibberish-class-name-styled-components-does-this-to-avoid-naming-conflictsnow-lets-style-our-button-component-const-defaultbutton-styledbutton-background-color-645cfc-border-none-padding-10px-color-white-defaultbutton-is-our-custom-component-name-after-we-style-it-we-can-give-it-any-html-tag-we-desire-so-that-this-custom-component-will-have-that-tagnow-we-will-use-defaultbutton-that-we-created-above-as-our-custom-component-in-reactjs-but-behind-the-scenes-it-will-be-the-button-tag-from-html-as-we-mentioned-in-styling-using-styled-componentsimport-styled-from-styled-components-const-h1-styledh1-color-red-const-defaultbutton-styledbutton-background-color-645cfc-border-none-padding-10px-color-white-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-export-default-appwe-can-also-keep-our-files-clean-by-making-a-different-file-for-each-different-component-in-styled-components-yes-we-can-do-that-in-herewe-will-make-new-folder-called-components-in-src-and-create-the-files-titlejs-and-buttonsjs-to-separate-the-styling-for-title-and-buttonswe-will-copy-the-h1-style-and-paste-it-into-titlejs-and-copy-defaultbutton-style-and-paste-it-in-buttonsjsin-titlejs-we-will-export-it-as-default-but-in-buttonsjs-we-will-name-the-export-because-we-will-create-multiple-button-styles-in-herewhen-we-are-exporting-a-component-as-default-then-its-import-is-a-regular-import-as-shown-belowimport-h1-from-componentstitlebut-when-the-export-is-a-named-export-you-can-see-the-named-export-in-buttonjs-in-the-above-image-then-while-importing-that-component-we-have-to-wrap-the-component-name-in-curly-braces-as-shown-belowimport-defaultbutton-from-componentsbuttonsnow-our-appjs-looks-like-thisimport-h1-from-componentstitle-import-defaultbutton-from-componentsbuttons-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-export-default-appprops-in-styled-componentsnow-for-those-of-you-who-know-props-from-react-youre-in-luck-pops-in-styled-components-work-similarly-if-you-dont-know-what-props-are-dont-worry-ill-introduce-them-herenow-we-learned-to-create-custom-components-in-styled-components-those-custom-components-can-have-attributes-which-we-can-access-in-components-it-might-be-a-bit-confusing-to-beginners-but-lets-see-it-in-codeimport-h1-from-componentstitle-import-defaultbutton-from-componentsbuttons-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-click-me-export-default-appin-the-above-code-i-created-one-more-default-button-but-can-you-see-difference-between-those-2-buttons-yes-we-have-something-written-after-defaultbutton-which-is-red-its-called-an-attributenow-by-accessing-the-attribute-in-defaultbutton-we-can-change-the-styling-based-on-these-attributes-lets-do-it-import-styled-from-styled-components-export-const-defaultbutton-styledbutton-background-color-props-gt-propsred-ampamp-red-645cfc-border-none-padding-10px-color-white-we-are-already-in-a-template-literal-backtickshttpsdevelopermozillaorgen-usdocswebjavascriptreferencetemplateliterals-so-we-can-write-javascript-inside-it-we-used-the-dollar-sign-and-curly-braces-to-write-the-javascript-in-those-curly-braces-we-declared-an-arrow-functionhttpsdevelopermozillaorgen-usdocswebjavascriptreferencefunctionsarrowfunctions-which-has-a-props-parameter-which-can-access-attributes-of-custom-componentsso-the-arrow-function-says-that-if-the-red-attribute-is-given-then-the-background-color-should-be-red-or-else-it-should-be-a-blueberry-colorappjsimport-h1-from-componentstitle-import-defaultbutton-from-componentsbuttons-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-click-me-export-default-appwe-can-also-destructure-props-by-attribute-name-above-we-gave-defaultbutton-an-attribute-of-red-and-we-accessed-it-with-propsredinstead-of-accessing-it-with-propsred-we-could-destructure-the-prop-with-and-the-attribute-name-refer-to-the-below-code-to-get-a-good-understanding-import-styled-from-styled-components-export-const-defaultbutton-styledbutton-background-color-red-gt-red-ampamp-red-645cfc-border-none-padding-10px-color-white-now-we-can-access-props-directly-as-red-rather-that-propsredhow-to-extend-styles-in-styled-componentswe-know-how-to-write-custom-styled-components-but-what-if-we-want-to-use-the-defaultbuttons-style-that-instead-has-100-width-of-the-button-we-can-do-that-using-extended-styles-in-styled-componentsits-simple-we-just-have-to-create-a-new-component-in-buttonsjs-and-well-use-styled-instead-of-styleddefaultbutton-now-our-new-component-will-have-added-the-styles-of-defaultbutton-and-some-of-new-styles-of-its-ownexport-const-extendedbutton-styleddefaultbutton-display-block-width-100vw-appjsimport-h1-from-componentstitle-import-defaultbutton-extendedbutton-from-componentsbuttons-function-app-return-styled-components-cillum-culpa-deserunt-enim-et-eiusmod-quis-proident-consequat-tempor-ipsum-sunt-esse-click-me-click-me-export-default-apphow-to-nest-styles-in-styled-componentswe-can-write-more-complex-styles-in-react-using-one-custom-component-this-will-help-you-even-more-and-make-styling-simple-refer-to-the-following-codeimport-styled-from-styled-components-function-app-return-another-heading-another-para-another-button-const-wrapper-styleddiv-h1-text-align-center-color-violet-p-font-size-40px-button-background-color-pink-padding-4px-8px-border-none-export-default-appwhen-we-implement-the-wrapper-component-all-paragraph-tags-inside-the-wrapper-will-have-a-font-size-of-40px-and-the-button-will-have-background-color-of-pink-padding-as-mentioned-and-no-border-this-will-help-you-tremendously-when-writing-your-codehow-to-extend-react-componentswe-can-also-extend-react-components-using-styled-components-it-is-pretty-similar-to-nesting-styles-heres-an-exampleimport-react-from-react-import-styled-from-styled-components-const-newcom-gt-return-heading-2-click-me-const-wrapper-stylednewcom-h2-color-green-text-align-center-button-padding-4px-10px-background-color-violet-border-none-export-default-wrapperwhen-we-write-styles-using-styled-components-we-have-to-just-extend-react-components-like-extending-styles-when-were-extending-styles-we-write-the-name-of-the-extended-style-here-we-will-write-the-name-of-the-component-to-extend-as-shown-in-the-above-codebut-still-its-not-working-if-we-inspect-we-will-see-our-html-but-with-no-class-in-react-components-there-is-no-class-so-you-need-to-add-props-to-the-react-component-and-consolelog-those-propsyou-will-see-our-gibberish-class-name-with-the-keyvalue-pair-like-classname-gibberish-classname-so-now-using-that-we-will-destructure-the-props-and-give-a-classname-to-the-div-of-that-component-of-classname-refer-to-the-below-exampleimport-react-from-react-import-styled-from-styled-components-const-newcom-classname-gt-return-heading-2-click-me-const-wrapper-stylednewcom-h2-color-green-text-align-center-button-padding-4px-10px-background-color-violet-border-none-export-default-wrappereven-after-using-styled-components-for-styling-you-can-use-global-stylingjust-remember-that-if-your-global-styling-and-styled-component-styling-are-the-same-react-will-pick-the-styled-component-stylingcss-variablesrepeating-the-same-color-is-annoying-what-if-i-have-red-in-many-places-and-now-i-want-all-that-red-changed-to-blue-it-is-a-time-consuming-task-to-do-manually-one-by-oneluckily-css-variables-come-to-our-rescue-now-create-an-indexcss-file-in-the-src-folder-import-it-in-indexjsimport-indexcssnow-we-will-write-some-css-variable-in-indexcss-which-are-global-styles-accessible-from-everywhere-the-most-interesting-thing-is-that-we-can-have-access-to-css-variables-in-styled-component-as-wellindexcssroot-primary-color-8f00ff-now-root-is-just-like-selecting-html-in-css-but-root-has-more-specificity-than-html-we-can-now-use-this-variable-in-our-styled-component-const-wrapper-stylednewcom-h2-color-green-text-align-center-button-padding-4px-10px-background-color-var-primary-color-border-none-how-to-add-a-themenowadays-light-themes-and-dark-themes-are-pretty-popular-we-can-do-this-easily-in-styles-componentsfirst-we-need-to-import-themeprovider-from-styled-components-then-we-will-wrap-the-whole-app-in-themeprovider-with-the-theme-attribute-in-which-we-will-provide-our-theme-then-we-can-toggled-it-with-reactimport-styled-themeprovider-from-styled-components-import-sample-from-componentssample-const-basetheme-background-fff-color-222-const-darktheme-background-222-color-fff-function-app-return-this-is-sample-paragraph-still-we-dont-get-our-dark-theme-for-that-we-need-to-add-a-new-custom-styled-component-you-can-name-it-anything-you-want-but-im-gonna-name-it-containerin-the-container-we-can-access-the-theme-and-its-properties-and-help-the-user-change-the-background-color-and-color-of-text-these-are-the-only-major-things-to-switch-in-between-dark-and-light-modeimport-styled-themeprovider-from-styled-components-import-sample-from-componentssample-const-basetheme-background-fff-color-222-const-darktheme-background-222-color-fff-const-container-styleddiv-color-props-gt-propsthemecolor-background-color-props-gt-propsthemebackground-function-app-return-this-is-sample-paragraph-take-a-look-at-our-container-we-are-accessing-the-theme-and-changing-the-color-and-background-color-when-the-theme-changes-and-here-you-go-a-simple-way-to-have-themes-on-your-next-projectanimation-in-styled-componentsanimation-is-important-in-frontend-development-we-will-learn-to-implement-animation-in-styled-components-with-an-examplefirst-we-have-to-import-keyframes-from-styled-components-once-thats-done-we-will-use-it-to-create-animationsimport-styled-keyframes-from-styled-components-const-spinner-keyframes-to-transform-rotate360deg-const-loading-styleddiv-width-6rem-height-6rem-border-5px-solid-ccc-border-radius-50-border-top-color-black-animation-spinner-06s-linear-infinite-export-default-loadingin-the-above-code-we-have-spinner-in-which-we-declared-the-animation-and-spinner-is-the-animation-name-in-loading-we-are-using-that-spinner-animation-name-so-that-loading-will-use-that-animation-in-loading-i-have-use-a-shorthand-property-to-declare-the-animationhow-to-use-as-in-styled-componentsif-i-have-a-button-and-i-give-it-an-href-attribute-which-we-use-to-link-to-another-website-it-will-not-work-this-is-because-the-href-attribute-belongs-to-the-anchor-tagimport-react-from-react-import-defaultbutton-from-componentsbuttons-const-app-gt-return-click-export-default-appbut-in-styles-component-using-as-we-can-make-the-given-component-act-like-an-html-tag-provided-as-a-value-to-as-lets-see-it-in-actionimport-react-from-react-import-defaultbutton-from-componentsbuttons-const-app-gt-return-click-export-default-appnow-defaultbutton-is-an-anchor-tag-it-will-have-text-decoration-because-in-the-default-anchor-tag-it-has-text-decoration-but-i-am-sure-now-you-can-work-that-out-when-we-click-on-our-defaultbutton-it-will-open-googlecss-and-styled-componentsnow-we-can-directly-give-styles-to-components-using-css-as-an-object-of-the-component-called-css-props-import-react-from-react-import-styled-from-styled-components-const-app-gt-return-hello-world-export-default-appbut-the-above-code-wont-work-because-we-need-to-import-styled-componentsmacro-to-activate-the-styling-method-which-uses-babel-check-out-the-complete-code-belowimport-react-from-react-import-styled-from-styled-componentsmacro-const-app-gt-return-hello-world-export-default-appcss-helper-functions-in-styled-componentswe-have-learned-a-lot-about-styled-components-but-there-are-more-efficient-ways-to-tackle-some-problems-and-one-of-them-is-using-a-css-helper-functionsuppose-you-want-a-defaultbutton-and-a-large-defaultbutton-based-on-what-weve-learned-up-until-now-we-would-say-we-should-give-large-as-a-prop-and-change-the-styling-based-on-that-propbut-think-about-it-we-need-to-make-changes-to-multiple-properties-so-a-css-helper-function-comes-to-our-rescue-appjsimport-react-from-react-import-styled-from-styled-componentsmacro-import-defaultbutton-from-componentsbuttons-const-app-gt-return-hello-hello-export-default-appbuttonsjsimport-styled-css-from-styled-componentsmacro-export-const-defaultbutton-styledbutton-background-color-red-gt-red-ampamp-red-645cfc-border-none-color-white-display-block-margin-10px-large-gt-large-css-padding-15px-font-weight-800-css-padding-10px-font-weight-400-take-a-look-at-the-above-code-first-we-passed-a-prop-as-large-from-appjs-in-defaultbutton-component-then-using-the-ternary-operator-in-buttonjs-we-styled-the-component-it-says-that-if-large-is-given-a-prop-implement-the-first-styling-or-else-implement-the-second-styling-this-follows-the-dry-dont-repeat-yourself-principledefault-attributes-attrs-in-styled-componentswe-have-attributes-on-some-elements-in-html-for-example-on-button-we-have-typesubmit-or-typebutton-but-every-time-we-have-to-set-them-manuallyimport-react-from-react-import-styled-from-styled-components-const-button-styledbutton-border-none-padding-5px-10px-background-color-87cd11-margin-10px-const-app-gt-return-click-submit-export-default-apphere-default-attributes-come-in-handy-we-can-pass-an-object-or-function-to-them-but-if-we-pass-objects-to-attributes-then-they-will-be-static-to-have-dynamic-control-we-will-pass-a-function-to-the-attributeimport-react-from-react-import-styled-from-styled-components-const-button-styledbuttonattrsprops-gt-return-type-propstype-button-border-none-padding-5px-10px-background-color-87cd11-margin-10px-const-app-gt-return-click-submit-export-default-appin-the-above-code-we-set-attributes-to-button-this-says-that-if-the-type-is-given-then-it-will-set-that-type-to-the-given-props-or-if-no-props-are-given-it-will-set-it-to-button-by-defaultas-a-challenge-you-can-go-ahead-and-use-a-css-helper-function-to-set-a-different-style-based-on-the-type-of-buttonwrapping-upi-hope-you-now-understand-how-to-use-styled-components-in-your-projects-do-let-me-know-what-you-think-thank-you-for-readingyou-can-follow-me-ontwitterhttpstwittercomkedar98linkedinhttpswwwlinkedincominkedar-makode-9833321aboriginalsubdomainininstagramhttpswwwinstagramcomkedar98">tag, a paragraph using a tag and a button using the tag.<code>App.js function App() { return ( &lt;div&gt; &lt;h1&gt;Styled Components&lt;/h1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;button&gt;Click ME!&lt;/button&gt; &lt;/div&gt; ); } export default App;</code>Before we style our component, we need to import styled-components into our <code>app.js</code> file:<code>import styled from 'styled-components' function App() { return ( &lt;div&gt; &lt;h1&gt;Styled Components&lt;/h1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;button&gt;Click ME!&lt;/button&gt; &lt;/div&gt; ); } export default App;</code>Now we will create our <strong>custom component</strong> called H1 and use it instead of the tag with custom styling.<code>const H1 = styled.h1` color: red; font-size: 4rem; ` </code>First we need give a custom name of our choice. Then we'll start with <code>styled.&lt;HTML Tag Name&gt;</code> and wrap the style in backticks. Now when we use this custom component it will have the <code>&lt;HTML Tag Name&gt;</code> property with styling.<code>import styled from 'styled-components' const H1 = styled.h1` color: red; font-size: 4rem; ` function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;button&gt;Click ME!&lt;/button&gt; &lt;/div&gt; ); } export default App;</code>Voilà! Here we have our first custom styled component.<strong>NOTE</strong>: Always use uppercase letters to start your custom component name in React as it is React convention.Now if you inspect the page, you will see some gibberish class name. Styled components does this to avoid naming conflicts.Now let's style our button component:<code>const DefaultButton = styled.button` background-color: #645cfc; border: none; padding: 10px; color: white; ` </code>DefaultButton is our custom component name. After we style it, we can give it any HTML tag we desire so that this custom component will have that tag.Now we will use DefaultButton that we created above as our custom component in React.js – but behind the scenes it will be the button tag from HTML as we mentioned in styling using styled components.<code>import styled from 'styled-components' const H1 = styled.h1` color: red; ` const DefaultButton = styled.button` background-color: #645cfc; border: none; padding: 10px; color: white; ` function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;DefaultButton&gt;Click ME!&lt;/DefaultButton&gt; &lt;/div&gt; ); } export default App;</code>We can also keep our files clean by making a different file for each different component in styled components. Yes! We can do that in here.We will make new folder called <code>components</code> in <code>src</code> and create the files <code>Title.js</code> and <code>Buttons.js</code> to separate the styling for title and buttons.We will copy the H1 style and paste it into <code>Title.js</code> and copy DefaultButton style and paste it in <code>Buttons.js</code>.In <code>Title.js</code> we will export it as default. But in <code>Buttons.js</code> we will name the export because we will create multiple button styles in here.When we are exporting a component as default, then its import is a regular import as shown below:<code>import H1 from './components/Title'</code>But when the export is a named export (you can see the named export in Button.js in the above image), then while importing that component we have to wrap the component name in curly braces ({}) as shown below:<code>import {DefaultButton} from './components/Buttons'</code>Now our <code>App.js</code> looks like this:<code>import H1 from './components/Title' import {DefaultButton} from './components/Buttons' function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;DefaultButton&gt;Click ME!&lt;/DefaultButton&gt; &lt;/div&gt; ); } export default App;</code>Props in Styled ComponentsNow for those of you who know props from React, you're in luck – pops in styled components work similarly. If you don't know what props are, don't worry – I'll introduce them here.Now, we learned to create custom components in styled components. Those custom components can have attributes which we can access in components. It might be a bit confusing to beginners but let's see it in code:<code>import H1 from './components/Title' import {DefaultButton} from './components/Buttons' function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;DefaultButton&gt;Click ME!&lt;/DefaultButton&gt; &lt;DefaultButton red&gt;Click ME!&lt;/DefaultButton&gt; &lt;/div&gt; ); } export default App;</code>In the above code, I created one more Default button. But can you see difference between those 2 buttons. Yes! We have something written after DefaultButton, which is <code>red</code>. It's called an attribute.Now by accessing the attribute in DefaultButton we can change the styling based on these attributes. Let's do it!<code>import styled from 'styled-components' export const DefaultButton = styled.button` background-color: ${(props) =&gt; (props.red &amp;&amp; 'red') || '#645cfc'}; border: none; padding: 10px; color: white; ` </code>We are already in a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">template literal (backticks)</a>. So we can write JavaScript inside it. We used the dollar ($) sign and curly braces to write the JavaScript. In those curly braces we declared an <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">arrow function</a> which has a props parameter which can access attributes of custom components.So the arrow function says that if the <strong>red</strong> attribute is given, then the background-color should be red or else it should be a blueberry color.<code>App.jsimport H1 from './components/Title' import {DefaultButton} from './components/Buttons' function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;DefaultButton&gt;Click ME!&lt;/DefaultButton&gt; &lt;DefaultButton red&gt;Click ME!&lt;/DefaultButton&gt; &lt;/div&gt; ); } export default App;</code>We can also destructure props by attribute name. Above, we gave DefaultButton an attribute of red and we accessed it with <code>props.red</code>.Instead of accessing it with <code>props.red</code> we could destructure the prop with {} and the attribute name. Refer to the below code to get a good understanding.<code>import styled from 'styled-components' export const DefaultButton = styled.button` background-color: ${({red}) =&gt; (red &amp;&amp; 'red') || '#645cfc'}; border: none; padding: 10px; color: white; ` </code>Now we can access props directly as <code>red</code> rather that <code>props.red</code>.How to Extend Styles in Styled ComponentsWe know how to write custom styled components. But what if we want to use the DefaultButtons style that instead has 100% width of the button? We can do that using extended styles in styled components.It's simple: we just have to create a new component in <code>Buttons.js</code> . And we'll use <code>styled.&lt;html Tag&gt;</code>, instead of <code>styled(DefaultButton)</code>. Now our new component will have added the styles of DefaultButton and some of new styles of its own.<code>export const ExtendedButton = styled(DefaultButton)` display: block; width: 100vw; `App.jsimport H1 from './components/Title' import {DefaultButton, ExtendedButton} from './components/Buttons' function App() { return ( &lt;div&gt; &lt;H1&gt;Styled Components&lt;/H1&gt; &lt;p&gt;Cillum culpa deserunt enim et eiusmod quis proident consequat tempor ipsum sunt esse.&lt;/p&gt; &lt;DefaultButton&gt;Click ME!&lt;/DefaultButton&gt; &lt;ExtendedButton red&gt;Click ME!&lt;/ExtendedButton&gt; &lt;/div&gt; ); } export default App;</code>How to Nest Styles in Styled ComponentsWe can write more complex styles in React using one custom component. This will help you even more and make styling simple. Refer to the following code:<code>import styled from 'styled-components' function App() { return ( &lt;div&gt; &lt;Wrapper&gt; &lt;h1&gt;Another heading&lt;/h1&gt; &lt;p&gt;Another para&lt;/p&gt; &lt;button&gt;Another button&lt;/button&gt; &lt;/Wrapper&gt; &lt;/div&gt; ); } const Wrapper = styled.div` h1{ text-align: center; color: violet; } p{ font-size: 40px; } button{ background-color: pink; padding: 4px 8px; border: none; } ` export default App;</code>When we implement the wrapper component, all paragraph tags inside the wrapper will have a font-size of 40px and the button will have background color of pink, padding as mentioned, and no border. This will help you tremendously when writing your code.How to Extend React ComponentsWe can also extend React components using styled components. It is pretty similar to nesting styles. Here's an example:<code>import React from 'react' import styled from 'styled-components' const Newcom = () =&gt; { return ( &lt;div&gt; &lt;h2&gt;Heading 2&lt;/h2&gt; &lt;button&gt;Click Me!&lt;/button&gt; &lt;/div&gt; ) } const Wrapper = styled(Newcom)` h2{ color: green; text-align: center; } button{ padding: 4px 10px; background-color: violet; border: none; } ` export default Wrapper</code>When we write styles using styled components, we have to just extend React components like extending styles. When we're extending styles, we write the name of the extended style. Here we will write the name of the component to extend as shown in the above code.But still it's not working. If we inspect we will see our HTML but with no class. In React components there is no class. So you need to add props to the React component and console.log() those props.You will see our gibberish class name with the key:value pair, like className : gibberish-classname. So now using that we will destructure the props and give a className to the div of that component of className. Refer to the below example:<code>import React from 'react' import styled from 'styled-components' const Newcom = ({className}) =&gt; { return ( &lt;div className={className}&gt; &lt;h2&gt;Heading 2&lt;/h2&gt; &lt;button&gt;Click Me!&lt;/button&gt; &lt;/div&gt; ) } const Wrapper = styled(Newcom)` h2{ color: green; text-align: center; } button{ padding: 4px 10px; background-color: violet; border: none; } ` export default Wrapper</code>Even after using styled components for styling you can use global styling.Just remember that if your global styling and styled component styling are the same, React will pick the styled component styling.CSS VariablesRepeating the same color is annoying. What if I have red in many places and now I want all that red changed to blue? It is a time consuming task to do manually, one by one.Luckily, CSS variables come to our rescue. Now create an <code>index.css</code> file in the <code>src</code> folder. Import it in <code>index.js</code>.<code>import './index.css';</code>Now we will write some CSS variable in index.css which are global styles accessible from everywhere. The most interesting thing is that we can have access to CSS variables in styled component as well.<code>index.css:root{ --primary-color: #8F00FF }</code>Now <code>:root{}</code> is just like selecting <code>html{}</code> in CSS. But <code>:root{}</code> has more specificity than <code>html{}</code>. We can now use this variable in our styled component:<code>const Wrapper = styled(Newcom)` h2{ color: green; text-align: center; } button{ padding: 4px 10px; background-color: var(--primary-color); border: none; } ` </code>How to Add a ThemeNowadays, light themes and dark themes are pretty popular. We can do this easily in styles components.First we need to import ThemeProvider from styled components. Then we will wrap the whole app in ThemeProvider with the theme attribute in which we will provide our theme. Then we can toggled it with React.<code>import styled, {ThemeProvider} from 'styled-components' import Sample from "./components/Sample"; const baseTheme = { background: '#fff', color: '#222', } const darkTheme = { background: '#222', color: '#fff', } function App() { return ( &lt;ThemeProvider theme={darkTheme}&gt; &lt;p&gt;This is sample paragraph&lt;/p&gt; &lt;/ThemeProvider&gt; ); }</code>Still, we don't get our dark theme. For that we need to add a new custom styled component. You can name it anything you want but, I'm gonna name it <code>Container</code>.In the container, we can access the theme and its properties and help the user change the background color and color of text. These are the only major things to switch in between dark and light mode.<code>import styled, {ThemeProvider} from 'styled-components' import Sample from "./components/Sample"; const baseTheme = { background: '#fff', color: '#222', } const darkTheme = { background: '#222', color: '#fff', } const Container = styled.div` color: ${(props) =&gt; props.theme.color}; background-color: ${(props) =&gt; props.theme.background}; ` function App() { return ( &lt;ThemeProvider theme={darkTheme}&gt; &lt;Container&gt; &lt;p&gt;This is sample paragraph&lt;/p&gt; &lt;/Container&gt; &lt;/ThemeProvider&gt; ); }</code>Take a look at our <code>Container</code>. We are accessing the theme and changing the color and background-color when the theme changes. And here you go, a simple way to have themes on your next project.Animation in Styled ComponentsAnimation is important in frontend development. We will learn to implement animation in styled components with an example.First we have to import keyframes from styled-components. Once that's done we will use it to create animations.<code>import styled, {keyframes} from 'styled-components' const spinner = keyframes` to{ transform: rotate(360deg); } ` const Loading = styled.div` width: 6rem; height: 6rem; border: 5px solid #ccc; border-radius: 50%; border-top-color: black; animation: ${spinner} 0.6s linear infinite; ` export default Loading</code>In the above code, we have spinner in which we declared the animation and spinner is the animation name. In loading, we are using that spinner animation name so that Loading will use that animation. In loading I have use a shorthand property to declare the animation.How to Use <code>as</code> in Styled ComponentsIf I have a button and I give it an <code>href</code> attribute which we use to link to another website, it will not work. This is because the <code>href</code> attribute belongs to the anchor tag.<code>import React from 'react' import {DefaultButton} from './components/Buttons' const App = () =&gt; { return ( &lt;div&gt; &lt;DefaultButton href="https://www.google.com"&gt;Click&lt;/DefaultButton&gt; &lt;/div&gt; ) } export default App</code>But in styles component using <code>as</code> we can make the given component act like an HTML tag provided as a value to <code>as</code>. Let's see it in action.<code>import React from 'react' import {DefaultButton} from './components/Buttons' const App = () =&gt; { return ( &lt;div&gt; &lt;DefaultButton as='a' href="https://www.google.com"&gt;Click&lt;/DefaultButton&gt; &lt;/div&gt; ) } export default App</code>Now DefaultButton is an anchor () tag. It will have text-decoration because in the default anchor tag it has text-decoration. But I am sure now you can work that out. When we click on our DefaultButton it will open Google.CSS and styled-componentsNow we can directly give styles to components using CSS as an object of the component called <code>css props</code> .<code>import React from 'react' import styled from 'styled-components' const App = () =&gt; { return ( &lt;div&gt; &lt;h2 css={`color: green`}&gt;Hello World!!!&lt;/h2&gt; &lt;/div&gt; ) } export default App</code>But the above code won't work. Because we need to import styled-components/macro to activate the styling method which uses Babel. Check out the complete code below:<code>import React from 'react' import styled from 'styled-components/macro' const App = () =&gt; { return ( &lt;div&gt; &lt;h2 css={`color: green`}&gt;Hello World!!!&lt;/h2&gt; &lt;/div&gt; ) } export default App</code>CSS Helper Functions in Styled ComponentsWe have learned a lot about styled components. But there are more efficient ways to tackle some problems – and one of them is using a CSS helper function.Suppose you want a DefaultButton and a large DefaultButton. Based on what we've learned up until now, we would say we should give large as a prop and change the styling based on that prop.But think about it – we need to make changes to multiple properties. So a CSS helper function comes to our rescue.<code>App.jsimport React from 'react' import styled from 'styled-components/macro' import {DefaultButton} from './components/Buttons' const App = () =&gt; { return ( &lt;div&gt; &lt;DefaultButton&gt;Hello&lt;/DefaultButton&gt; &lt;DefaultButton large&gt;Hello&lt;/DefaultButton&gt; &lt;/div&gt; ) } export default AppButtons.jsimport styled, {css} from 'styled-components/macro' export const DefaultButton = styled.button` background-color: ${({red}) =&gt; (red &amp;&amp; 'red') || '#645cfc'}; border: none; color: white; display: block; margin: 10px; ${({large}) =&gt; large? css` padding: 15px; font-weight: 800; ` : css` padding: 10px; font-weight: 400; `} ` </code>Take a look at the above code. First we passed a prop as large from app.js in DefaultButton component. Then using the ternary operator in Button.js we styled the component. It says that if <code>large</code> is given a prop, implement the first styling or else implement the second styling. This follows the DRY (Don't Repeat Yourself) principle.Default Attributes (attrs) in Styled ComponentsWe have attributes on some elements in HTML. For example on button, we have type="submit" or type="button". But every time we have to set them manually.<code>import React from 'react' import styled from 'styled-components' const Button = styled.button` border: none; padding: 5px 10px; background-color: #87CD11; margin: 10px; ` const App = () =&gt; { return ( &lt;div&gt; &lt;Button type="button"&gt;Click!&lt;/Button&gt; &lt;Button type="submit"&gt;Submit&lt;/Button&gt; &lt;/div&gt; ) } export default App</code>Here, default attributes come in handy. We can pass an object or function to them. But if we pass objects to attributes, then they will be static. To have dynamic control, we will pass a function to the attribute.<code>import React from 'react' import styled from 'styled-components' const Button = styled.button.attrs((props) =&gt; { return {type: props.type || "button"} })` border: none; padding: 5px 10px; background-color: #87CD11; margin: 10px; ` const App = () =&gt; { return ( &lt;div&gt; &lt;Button&gt;Click!&lt;/Button&gt; &lt;Button type="submit"&gt;Submit&lt;/Button&gt; &lt;/div&gt; ) } export default App</code>In the above code, we set attributes to <code>button</code>. This says that if the type is given then it will set that type to the given props – or if no props are given it will set it to button by default.As a challenge, you can go ahead and use a CSS helper function to set a different style based on the type of button.<strong>Wrapping Up</strong>I hope you now understand how to use Styled Components in your projects. Do let me know what you think. Thank you for reading!You can follow me on:<a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a><a target="_blank" href="https://www.instagram.com/kedar_98/">Instagram</a></h1>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React + WebSockets Project – Build a Real-Time Order Book Application ]]>
                </title>
                <description>
                    <![CDATA[ In this tutorial, we will see how to build an Order Book web application, that we'll use to display real-time cryptocurrency info. We will use React with Typescript for creating the UI, Redux for managing the application state, and styled-components ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-websockets-project-build-real-time-order-book-app/</link>
                <guid isPermaLink="false">66d4605e230dff0166905835</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Redux ]]>
                    </category>
                
                    <category>
                        <![CDATA[ styled-components ]]>
                    </category>
                
                    <category>
                        <![CDATA[ websocket ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Mihail Gaberov ]]>
                </dc:creator>
                <pubDate>Tue, 19 Apr 2022 17:15:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/04/react-and-websockets-articlde.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this tutorial, we will see how to build an Order Book web application, that we'll use to display real-time cryptocurrency info.</p>
<p>We will use <a target="_blank" href="https://create-react-app.dev/docs/adding-typescript/">React with Typescript</a> for creating the UI, <a target="_blank" href="https://redux.js.org/">Redux</a> for managing the application state, and <a target="_blank" href="https://styled-components.com/">styled-components</a> for applying the styling. And last, but not least, we'll use <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket">WebSockets</a> for fetching the data feeds.</p>
<h3 id="heading-github-repo">GitHub Repo</h3>
<p>💡 If you want to skip the reading, <a target="_blank" href="https://github.com/mihailgaberov/orderbook">here</a> 💁 is the GitHub repository with a detailed <a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/main/README.md">README</a> 🙌, and <a target="_blank" href="https://orderbook-mihailgaberov.vercel.app/">here</a> you can see the live demo.</p>
<h2 id="heading-what-is-an-order-book">What is an Order Book?</h2>
<p>An <a target="_blank" href="https://www.coindesk.com/crypto-trading-101-how-to-read-an-exchange-order-book">Order Book</a> is an application that usually displays some kind of information related to buying and selling stuff.</p>
<p>💡 The most common use case is showing data for various assets, such as stocks, bonds, currencies, and even cryptocurrencies.</p>
<h2 id="heading-why-would-i-need-an-order-book">Why Would I Need an Order Book?</h2>
<p>In practice, Order Books are used by traders to watch the fluctuations of the bidding price and the asking price of certain products – currencies, stocks, and so on.</p>
<p>This is happening real time, so the changes can be very rapid. Here is where WebSockets will come in handy, as you will see later.</p>
<p>In the past, people did something similar on paper, but the ‘real-time' part was impossible, of course.</p>
<p>A regular Order Book usually has two sides: buying (or bidding), shown in green on the left side and selling (or asking), red, on the right.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/image-43.png" alt="Classic Orderbook" width="600" height="400" loading="lazy"></p>
<p><em>Classic Order book</em></p>
<h2 id="heading-the-plan-for-our-order-book-app">The Plan for our Order Book App</h2>
<p>Our Order Book app will consist of five parts:</p>
<ul>
<li><p>order book main view</p>
</li>
<li><p>grouping select box</p>
</li>
<li><p>Toggle Feed button</p>
</li>
<li><p>Kill Feed button</p>
</li>
<li><p>Status Message.</p>
</li>
</ul>
<p>The app design will look as shown below. Note that the Status Message component, that you will see in the my implementation, is missing on these screenshots:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/image-60.png" alt="Desktop layout" width="600" height="400" loading="lazy"></p>
<p><em>Desktop layout</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/image-61.png" alt="Mobile layout" width="600" height="400" loading="lazy"></p>
<p><em>Mobile layout</em></p>
<h2 id="heading-application-features"><strong>Application Features</strong></h2>
<h3 id="heading-order-book">Order book</h3>
<p>The order book has two sides: the buy side and the sell side.</p>
<p>Both sides contain information about the number of orders opened at each price level.</p>
<p>Each level displays:</p>
<ul>
<li><p><strong>Price</strong>: this is what defines the level. As orders must be placed at a price that is a multiple of the selected market's tick size (0.5), each level will be an increment of 0.5 (as long as there is an order open at that level).</p>
</li>
<li><p><strong>Size</strong>: the total quantity of contracts derived from open orders that have been placed at this level.</p>
</li>
<li><p><strong>Total</strong>: the summed amount of contracts derived from open orders that reside in the book at this level and above. To calculate the total of a given level we take the size of the current level and sum the sizes leading to this price level in the order book. The total is also used to calculate the depth visualizer (colored bars behind the levels). The depth of each level is calculated by taking that level's total as a percentage of the highest total in the book.</p>
</li>
</ul>
<h3 id="heading-grouping-select-box">Grouping Select Box</h3>
<p>By default the orders are grouped by the selected market's ticket size (0.5).</p>
<p>Possible toggling of the grouping is between 0.5, 1, 2.5 for XBTUSD market and 0.05, 0.1 and 0.25 for ETHUSD market.</p>
<p>To group levels, we combine the levels rounded down to the nearest group size – for example, if we change our grouping from 0.5 to 1 then we would combine the data from prices 1000 and 1000.5 and display it under a single level in the order book with the price 1000.</p>
<h3 id="heading-toggle-feed-button">Toggle Feed Button</h3>
<p>This button toggles the selected market between PI_XBTUSD and PI_ETHUSD. These are the two markets we will support -&gt; Bitcoin/USD and Ethereum/USD.</p>
<p>It supports dynamic grouping logic and handles groupings for XBT (0.5, 1, 2.5) and groupings for ETH (0.05, 0.1, 0.25).</p>
<h3 id="heading-kill-feed-button">Kill Feed Button</h3>
<p>Clicking this button stops the feed.</p>
<p>Then clicking this button a second time renews the feed.</p>
<h3 id="heading-status-message">Status Message</h3>
<p>This message will show the currently selected market. It will also show a message saying the feed is killed.</p>
<h2 id="heading-tech-stack-for-our-app">Tech Stack for our App</h2>
<p>Here is a list of the main technologies we will be using:</p>
<ul>
<li><p><a target="_blank" href="https://create-react-app.dev/docs/adding-typescript/">React with TypeScript</a> (<code>yarn create react-app my-app --template typescript</code>) — a UI library we will use for building our application’s user interfaces.</p>
</li>
<li><p><a target="_blank" href="https://redux.js.org/">Redux</a> — a state management library we will use for managing our application’s state.</p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">WebSockets</a> — The <code>WebSocket</code> object provides the API for creating and managing a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">WebSocket</a> connection to a server, as well as for sending and receiving data on the connection. We will use it to implement the logic for consuming the live feeds as well as to be able to stop and renew.</p>
</li>
<li><p><a target="_blank" href="https://www.styled-components.com/docs">styled-components</a> — a CSS-in-JS library that lets you define the CSS styles of your components using ES6 template literals. We will use it to add styles to our app and make the look and feel beautiful. It utilizes tagged template literals to style your components and 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.</p>
</li>
<li><p><a target="_blank" href="https://github.com/testing-library/react-testing-library">react-testing-library</a> — The <code>React Testing Library</code> is a very light-weight solution for testing React components. We will use it for testing the UI components of our app.</p>
</li>
<li><p><a target="_blank" href="https://jestjs.io/">Jest</a> - a JavaScript Testing Framework that has become the de facto standard when we talk about testing React applications. We will use it to write some unit tests that will cover the reducer functions we have in our app.</p>
</li>
</ul>
<h2 id="heading-how-to-build-the-app">How to Build the App</h2>
<p>From this point onward I will try to guide you through the process I followed when building this.</p>
<p>💡 I must say that what I am showing you here is just <strong>a way</strong> of creating such an app – but it's not <strong>the way</strong> in any regard. Probably folks with more experience in crypto would do it better.</p>
<h3 id="heading-project-structure">Project Structure</h3>
<p>The project structure is pretty straightforward. We are using React and styled-components, which makes this way of structuring very convenient.</p>
<p>Let's see first what it looks like and then I will explain the what and the why.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/image-31.png" alt="Project structure" width="600" height="400" loading="lazy"></p>
<p><em>Project structure</em></p>
<p>As you can see on the image above, I have organized most of the components in folders. Each folder contains an <code>index.tsx</code> file, a <code>styles.tsx</code> and a <code>.test.tsx</code> files.</p>
<p><strong>index.tsx</strong> – contains the code responsible for the component logic.</p>
<p><strong>styles.tsx</strong> – contains the code responsible for styling the component. Here is where styled-components shines.</p>
<p><strong>.text.tsx</strong> – these contain the component unit tests.</p>
<p>Let me give you a short summary of the idea behind each of the components in the <code>components</code> folder. Starting top to bottom:</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/Button">Button</a> renders a button with a given background color and title. It's used for the two buttons in the footer, <code>Toggle Feed</code> and <code>Kill Feed / Renew Feed</code>.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/DepthVisualizer">DepthVisualizer</a> is the component responsible for drawing the red and the green backgrounds you are seeing behind the numbers. It does this by rendering a row (an HTML <code>div</code> element) with given width, position being left (Bids) or right (Asks).</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/Footer">Footer</a> – well, there's not much to say here, it contains the two buttons used in the app.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/GroupingSelectBox">GroupingSelectBox</a> renders the select box we use to change the grouping value, using setGrouping reducer to amend the application state when grouping is being changed.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/Header">Header</a> renders the title of the application as well as the GroupingSelectBox component.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/Loader">Loader</a> renders loading animation implemented by leveraging <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/SVG">SVG</a>.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/OrderBook">Order Book</a> contains the core logic of the app. Separated components are located in sub-folders, and the Redux state management logic is here also.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/Spread">Spread</a> renders the spread value, displayed in the middle of the header (in desktop view). The component itself contains short methods for calculating the amount itself and the percentage value.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/StatusMessage">StatusMessage</a> is a small component used to display <em>status messages.</em> It basically shows which market is currently being displayed and whether the feed is killed.</p>
<h3 id="heading-rendering-performance"><strong>Rendering Performance</strong></h3>
<p>Here is a good moment to talk about <em>rendering performance</em> and <em>inline styling</em> a bit.</p>
<p><strong>Rendering</strong> is the process of React asking your components to describe what they want their section of the UI to look like based on the current combination of props and state.</p>
<p>This process is triggered by a change of the state in your component. This change could be caused by some of the props being changed or by some internal logic of the component.</p>
<p>The point here is that when re-rendering happens unnecessarily, it reduces the performance of our app. This is exactly what happened to me when I introduced the initial implementation of the <em>DepthVisualizer</em> component. It was using styled-components, that is JavaScript, for the drawing part.</p>
<p>In order to solve this, I have changed the component to use inline styles, that is pure CSS, instead of a CSS in JS approach. In other words, my bottleneck was using JavaScript animations, which is a famous reason for reduced performance.</p>
<p>Here is how it looks like now:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> DepthVisualizer: FunctionComponent&lt;DepthVisualizerProps&gt; = <span class="hljs-function">(<span class="hljs-params">{windowWidth, depth, orderType }</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{{</span>
    <span class="hljs-attr">backgroundColor:</span> `${<span class="hljs-attr">orderType</span> === <span class="hljs-string">OrderType.BIDS</span> ? <span class="hljs-attr">DepthVisualizerColors.BIDS</span> <span class="hljs-attr">:</span> <span class="hljs-attr">DepthVisualizerColors.ASKS</span>}`,
    <span class="hljs-attr">height:</span> "<span class="hljs-attr">1.250em</span>",
    <span class="hljs-attr">width:</span> `${<span class="hljs-attr">depth</span>}%`,
    <span class="hljs-attr">position:</span> "<span class="hljs-attr">relative</span>",
    <span class="hljs-attr">top:</span> <span class="hljs-attr">21</span>,
    <span class="hljs-attr">left:</span> `${<span class="hljs-attr">orderType</span> === <span class="hljs-string">OrderType.BIDS</span> &amp;&amp; <span class="hljs-attr">windowWidth</span> &gt;</span> MOBILE_WIDTH ? `${100 - depth}%` : 0}`,
    marginTop: -24,
    zIndex: 1,
  }} /&gt;</span>;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> DepthVisualizer;
</code></pre>
<p><em>Inline styling</em> is when you write your CSS along with your markup, as values for the <code>style</code> attribute. This is something that is NOT considered a good practice, but as you can see here, there are cases when it's necessary to use it.</p>
<p>💡 Usually you would extract your CSS code into a separate file.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/Footer">Footer</a> a simple dummy component used to render the two buttons in the footer of the app.</p>
<p>Dummy components, also known as stateless or representational ones, are components that don't hold state and are usually used just to visualize data in some way. This data is being passed via the props. For example the <code>isFeedKilled</code> flag in the component above.</p>
<p>If such a component needs to execute some kind of interaction, it usually does this by accepting (again via the props, for example <code>toggleFeedCallback</code>) callback functions that can be executed when that interaction happens. For example clicking a button.</p>
<p>On the opposite side we could have smart or state-full components. They are the ones that are connected to the app state and can manipulate it directly. Usually they are the ones that read the data from the state and pass it to the stateless components via their props.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/GroupingSelectBox">GroupingSelectBox</a> contains the Select element you can use to switch between the groupings.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/main/src/components/Header/index.tsx">Header</a> is the header part of the app. It takes care of setting properly the layout consisting of the title 'Order Book' on the left and the select box on the right.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/Loader">Loader</a> is used as an indicator for when the data has not yet been loaded. It leverages a SVG animation I have found online.</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/tree/main/src/components/OrderBook">Order Book</a> is where the real thing is happening. This one consists of a few smaller components:</p>
<ul>
<li><p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/d8db0239763dce32fbcae499a6b7deefed9f684f/src/components/OrderBook/styles.tsx#L21">TableContainer</a> – used for styling the views for both the Odds and Bets sides.</p>
</li>
<li><p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/main/src/components/OrderBook/TitleRow/index.tsx">TitleRow</a> – this is the component responsible for displaying the titles of the columns: prize, size, and total, respectively.</p>
</li>
</ul>
<h3 id="heading-how-to-build-the-ui-with-react-and-styled-components">How to Build the UI with React and styled-components</h3>
<p>When we talk about component-based structure, such as the one <a target="_blank" href="https://reactjs.org/">React</a> provides us, the <a target="_blank" href="https://styled-components.com/">styled-components library</a> is likely one of the first choices you might make when styling is needed.</p>
<p>Like <a target="_blank" href="https://www.joshwcomeau.com/">Josh Comeau</a> says in his detailed <a target="_blank" href="https://www.joshwcomeau.com/css/styled-components/">article</a>:</p>
<blockquote>
<p>💡 It's a wonderful tool. In many ways, it's changed how I think about CSS architecture, and has helped me keep my codebase clean and modular, just like React!</p>
</blockquote>
<p>As the name of the lib hints, we could easily style our components by using the <a target="_blank" href="https://reactjs.org/docs/faq-styling.html#what-is-css-in-js">CSS-in-JS pattern</a>. Here is an example of how I used it to write the styles for my <code>Button</code> component:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">"styled-components"</span>;

interface ContainerProps {
  <span class="hljs-attr">backgroundColor</span>: string;
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Container = styled.button&lt;ContainerProps&gt;<span class="hljs-string">`
  padding: .3em .7em;
  margin: 1em;
  border-radius: 4px;
  border: none;
  color: white;
  background: <span class="hljs-subst">${props =&gt; props.backgroundColor}</span>;
  font-family: "Calibri", sans-serif;
  font-size: 1.2em;

  &amp;:hover {
    cursor: pointer;
    opacity: .8;
  }
`</span>
</code></pre>
<p>Notice how I am using an <code>interface</code> in my styles file, and also the <code>background</code> property being passed as an argument via <code>props</code>. This is part of the CSS-in-JS story.</p>
<p>The possibility to use CSS code in JavaScript or (as someone might say) vice versa comes very handy. For example, when we need a component to look differently depending on something, we can pass through its props a parameter to define this.</p>
<p>As every style is actually a component, this way of writing styles feels a lot like writing React components. I mean, in the end, everything is components, right?</p>
<h3 id="heading-responsiveness-and-page-visibility-detection">Responsiveness and Page Visibility Detection</h3>
<p>While working on this app, I read in several places that, for applications which support rapid updates, is a good practice to implement some kind of mechanism for pausing the whole thing when it is not being used by the user. For example when the user minimizes the browser window or just opens another tab.</p>
<p>Since our Order book is consuming a lot of new chunks of data every second via WSS, I decided to implement such a mechanism as well.</p>
<p>What this does is:</p>
<ul>
<li><p>it shows a loader when the data is not there yet</p>
</li>
<li><p>it changes the meta title to signify that the app is in <code>paused</code> mode</p>
</li>
<li><p>it unpauses the work once the app window is on focus</p>
</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-114.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Active mode</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-115.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Paused mode</em></p>
<p>You may see the whole implementation <a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/main/src/App.tsx">here</a>.</p>
<p>The essential part is in the useEffect hook, which is triggered only once when the application renders for first time.</p>
<p>In there we take advantage of the Page Visibility API by attaching the necessary listeners. And then, in the <a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/e74dfad48990ff1a1f12ac45f5a065cc5044ee75/src/App.tsx#L61">handlers</a>, we simply execute the logic we want.</p>
<h3 id="heading-window-size-detection">Window Size Detection</h3>
<p>In almost every app that has some level of responsiveness, you need some logic for detecting the changes in the window size and taking some actions accordingly.</p>
<p>In other words, you need to know when your app is being viewed in certain screen size, so you can arrange your components and adjust your styles so that everything looks nice and in place.</p>
<p>This is especially valid for mobile friendly applications, where responsiveness is essential.</p>
<p>Our implementation of the window size change detection is based on the <code>innerWidtgh</code> property of the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth">browser window object</a> and <code>onresize</code> event that is being triggered when it gets resized.</p>
<p>I am attaching a listener for this event in a <code>useEffect</code> hook in <a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/bd24e610e9fc4e271a6820a297b78decf4950fd9/src/App.tsx#L32">App.tsx file</a>. And then, every time the window size changes, I am setting the new width to a state variable via <code>setWindowWidth</code> hook.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> [windowWidth, setWindowWidth] = useState(<span class="hljs-number">0</span>);
...
...

<span class="hljs-comment">// Window width detection</span>
useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">window</span>.onresize = <span class="hljs-function">() =&gt;</span> {
    setWindowWidth(<span class="hljs-built_in">window</span>.innerWidth);
  }
  setWindowWidth(<span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">window</span>.innerWidth);
}, []);
</code></pre>
<p>Then propagate this variable down through all interested components and use it accordingly. For example here is how I use it in <a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/main/src/components/OrderBook/index.tsx">Order Book/index.tsx</a> in order to know when and where to render the TitleRow component.</p>
<pre><code class="lang-jsx">{windowWidth &gt; MOBILE_WIDTH &amp;&amp; <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">TitleRow</span> <span class="hljs-attr">windowWidth</span>=<span class="hljs-string">{windowWidth}</span> <span class="hljs-attr">reversedFieldsOrder</span>=<span class="hljs-string">{false}</span> /&gt;</span></span>}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-142.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>TitleRow component - desktop view</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-143.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>TitleRow component - mobile view</em></p>
<p>Note that it appears on different position depending on that whether you are seeing the app on desktop or mobile.</p>
<p>You may take a look at the <a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/main/src/components/OrderBook/TitleRow/index.tsx">component</a> itself and see similar approach of using the window width there.</p>
<h3 id="heading-state-management-with-redux">State Management with Redux</h3>
<p>As you probably guessed already, I used <a target="_blank" href="https://redux.js.org/">Redux</a> for managing the state of the app.</p>
<p>The main logic behind that is concentrated in the <a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/main/src/components/OrderBook/orderbookSlice.ts">orderbookSlice</a> reducer. In the following few lines I will walk you through it and see how and why I built it that way.</p>
<p>First we define the interface and the initial state of our order book data. The initial state contains the default values we need to have in place when starting the app.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> interface OrderbookState {
  <span class="hljs-attr">market</span>: string;
  rawBids: number[][];
  bids: number[][];
  maxTotalBids: number;
  rawAsks: number[][];
  asks: number[][];
  maxTotalAsks: number;
  groupingSize: number;
}

<span class="hljs-keyword">const</span> initialState: OrderbookState = {
  <span class="hljs-attr">market</span>: <span class="hljs-string">'PI_XBTUSD'</span>, <span class="hljs-comment">// PI_ETHUSD</span>
  <span class="hljs-attr">rawBids</span>: [],
  <span class="hljs-attr">bids</span>: [],
  <span class="hljs-attr">maxTotalBids</span>: <span class="hljs-number">0</span>,
  <span class="hljs-attr">rawAsks</span>: [],
  <span class="hljs-attr">asks</span>: [],
  <span class="hljs-attr">maxTotalAsks</span>: <span class="hljs-number">0</span>,
  <span class="hljs-attr">groupingSize</span>: <span class="hljs-number">0.5</span>
};
</code></pre>
<p>Then there are a few short, self-explanatory methods helping to manipulate the levels data:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> removePriceLevel = (price: number, <span class="hljs-attr">levels</span>: number[][]): number[][] =&gt; levels.filter(<span class="hljs-function"><span class="hljs-params">level</span> =&gt;</span> level[<span class="hljs-number">0</span>] !== price);

<span class="hljs-keyword">const</span> updatePriceLevel = (updatedLevel: number[], <span class="hljs-attr">levels</span>: number[][]): number[][] =&gt; {
  <span class="hljs-keyword">return</span> levels.map(<span class="hljs-function"><span class="hljs-params">level</span> =&gt;</span> {
    <span class="hljs-keyword">if</span> (level[<span class="hljs-number">0</span>] === updatedLevel[<span class="hljs-number">0</span>]) {
      level = updatedLevel;
    }
    <span class="hljs-keyword">return</span> level;
  });
};

<span class="hljs-keyword">const</span> levelExists = (deltaLevelPrice: number, <span class="hljs-attr">currentLevels</span>: number[][]): <span class="hljs-function"><span class="hljs-params">boolean</span> =&gt;</span> currentLevels.some(<span class="hljs-function"><span class="hljs-params">level</span> =&gt;</span> level[<span class="hljs-number">0</span>] === deltaLevelPrice);

<span class="hljs-keyword">const</span> addPriceLevel = (deltaLevel: number[], <span class="hljs-attr">levels</span>: number[][]): number[][] =&gt; {
  <span class="hljs-keyword">return</span> [ ...levels, deltaLevel ];
};
</code></pre>
<p>Then the real magic is happening. If the size returned by a delta is 0 then that price level should be removed from the order book. Otherwise you can safely overwrite the state of that price level with new data returned by that delta.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">/** The orders returned by the feed are in the format
 of [price, size][].
 * <span class="hljs-doctag">@param </span>currentLevels Existing price levels - `bids` or `asks`
 * <span class="hljs-doctag">@param </span>orders Update of a price level
 */</span>
<span class="hljs-keyword">const</span> applyDeltas = (currentLevels: number[][], <span class="hljs-attr">orders</span>: number[][]): number[][] =&gt; {
  <span class="hljs-keyword">let</span> updatedLevels: number[][] = currentLevels;

  orders.forEach(<span class="hljs-function">(<span class="hljs-params">deltaLevel</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> deltaLevelPrice = deltaLevel[<span class="hljs-number">0</span>];
    <span class="hljs-keyword">const</span> deltaLevelSize = deltaLevel[<span class="hljs-number">1</span>];

    <span class="hljs-comment">// If new size is zero - delete the price level</span>
    <span class="hljs-keyword">if</span> (deltaLevelSize === <span class="hljs-number">0</span> &amp;&amp; updatedLevels.length &gt; ORDERBOOK_LEVELS) {
      updatedLevels = removePriceLevel(deltaLevelPrice, updatedLevels);
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-comment">// If the price level exists and the size is not zero, update it</span>
      <span class="hljs-keyword">if</span> (levelExists(deltaLevelPrice, currentLevels)) {
        updatedLevels = updatePriceLevel(deltaLevel, updatedLevels);
      } <span class="hljs-keyword">else</span> {
        <span class="hljs-comment">// If the price level doesn't exist in the orderbook and there are less than 25 levels, add it</span>
        <span class="hljs-keyword">if</span> (updatedLevels.length &lt; ORDERBOOK_LEVELS) {
          updatedLevels = addPriceLevel(deltaLevel, updatedLevels);
        }
      }
    }
  });

  <span class="hljs-keyword">return</span> updatedLevels;
}
</code></pre>
<p>What follows after these are few helper methods. Let me say a few words about each of them now:</p>
<ul>
<li><p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/e74dfad48990ff1a1f12ac45f5a065cc5044ee75/src/components/OrderBook/orderbookSlice.ts#L82">addTotalSums</a> – with the help of this method, we iterate through the orders data, bids or asks, and calculate for each of them the total sum. The total sum value is then used for making the background visualizations.</p>
</li>
<li><p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/e74dfad48990ff1a1f12ac45f5a065cc5044ee75/src/components/OrderBook/orderbookSlice.ts#L99">addDepths</a> – we use this method to calculate the so-called <em>depth</em> for each order. These values will be used later by the depth meter component to display the red and green rows in the background.</p>
</li>
<li><p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/e74dfad48990ff1a1f12ac45f5a065cc5044ee75/src/components/OrderBook/orderbookSlice.ts#L113">getMaxTotalSum</a> – this one returns the max value of all total sums.</p>
</li>
</ul>
<p>Everything below is what we use for creating the application state. As per the <a target="_blank" href="https://redux-toolkit.js.org/rtk-query/overview#create-an-api-slice">Redux Toolkit documentation</a>, it’s using <code>createSlice</code>API to create the <em>slice</em>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-116.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Redux state</em></p>
<p>Creating a slice requires a string name to identify the slice, an initial state value, and one or more reducer functions to define how the state can be updated.</p>
<p>Once a slice is created, we can export the generated Redux action creators and the reducer function for the whole slice.</p>
<p>The last few lines consist of the exports in question – action creators, state slices selectors and the main reducer.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> { addBids, addAsks, addExistingState, setGrouping, clearOrdersState } = orderbookSlice.actions;
</code></pre>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> selectBids = (state: RootState): number[][] =&gt; state.orderbook.bids;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> selectAsks = (state: RootState): number[][] =&gt; state.orderbook.asks;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> selectGrouping = (state: RootState): <span class="hljs-function"><span class="hljs-params">number</span> =&gt;</span> state.orderbook.groupingSize;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> selectMarket = (state: RootState): <span class="hljs-function"><span class="hljs-params">string</span> =&gt;</span> state.orderbook.market;
</code></pre>
<pre><code class="lang-jsx"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> orderbookSlice.reducer;
</code></pre>
<p>With all that, our state manipulation logic is complete. 🎉</p>
<p>Now it’s time to take a look at the protocol we used in our app to take advantage of all these rapid changes in the data we consume.</p>
<h3 id="heading-websocket-protocol-wss">Websocket Protocol (WSS)</h3>
<p>As you may have noticed, we're using the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/WebSocket">Web Socket</a> communication protocol for fetching data into our application. We also use its features, as you will see in a moment, to accomplish other things (such as toggling the feeds and subscribe/unsubscribe from the data channel).</p>
<p><a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/main/src/components/OrderBook/index.tsx">Here</a> is how I used it.</p>
<p>Instead of trying to rely on manual implementation, I used the <a target="_blank" href="https://www.npmjs.com/package/react-use-websocket">react-use-websocket</a> package. It gives you all you need when you want to leverage WSS in a React app. If you want to go into details about this, you may take a look at their <a target="_blank" href="https://github.com/robtaussig/react-use-websocket#readme">documentation</a>.</p>
<h3 id="heading-a-few-words-about-my-implementation">A Few Words About My Implementation</h3>
<p>What we need fist is the endpoint URL where the data feeds are coming from. I am sure there are multiple options out there when we talk about cryptocurrencies. In our app I used the one provided by <a target="_blank" href="http://www.cryptofacilities.com/">www.cryptofacilities.com/</a>.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> WSS_FEED_URL: string = <span class="hljs-string">'wss://www.cryptofacilities.com/ws/v1'</span>;
</code></pre>
<p>Then the only thing we need to do to start consuming the data is to put the <code>useWebSocket</code> hook to work. As you may have guessed already, this hook is provided by the package mentioned above.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> useWebSocket <span class="hljs-keyword">from</span> [<span class="hljs-string">"react-use-websocket"</span>](<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">https:</span>//<span class="hljs-attr">github.com</span>/<span class="hljs-attr">robtaussig</span>/<span class="hljs-attr">react-use-websocket</span>&gt;</span></span>);

...
...
...

const { sendJsonMessage, getWebSocket } = useWebSocket(WSS_FEED_URL, {
    <span class="hljs-attr">onOpen</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'WebSocket connection opened.'</span>),
    <span class="hljs-attr">onClose</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'WebSocket connection closed.'</span>),
    <span class="hljs-attr">shouldReconnect</span>: <span class="hljs-function">(<span class="hljs-params">closeEvent</span>) =&gt;</span> <span class="hljs-literal">true</span>,
    <span class="hljs-attr">onMessage</span>: <span class="hljs-function">(<span class="hljs-params">event: WebSocketEventMap[<span class="hljs-string">'message'</span>]</span>) =&gt;</span>  processMessages(event)
  });
</code></pre>
<p>We pass the endpoint as the first argument and a few callback functions after that. These help us perform certain actions when one of the following happens:</p>
<ul>
<li><p><code>onOpen</code> – what to do when WebSocket connection is established.</p>
</li>
<li><p><code>onClose</code> – what to do when WebSocket connection is terminated.</p>
</li>
<li><p><code>shouldReconnect</code> – this is just a flag, saying if we want automatic reconnect when the connection drops for some reason.</p>
</li>
<li><p><code>onMessage</code> – this is the main event that brings us the chunks with the data (I call <code>processMessage</code> method every time when that happens. This means that every time when a new chunk of data is received, we process it and display it respectively).</p>
</li>
</ul>
<p>Down below is the method in question. It simply does two things:</p>
<ul>
<li><p>Either calls a method called <code>process</code> (No pun intended 😄) – this method is called every time new data for bids or asks is received and it processes it accordingly.</p>
</li>
<li><p>Dispatches an event that is using one of the <a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/e74dfad48990ff1a1f12ac45f5a065cc5044ee75/src/components/OrderBook/orderbookSlice.ts#L148">reducer functions</a> we have seen earlier. This function practically creates the initial state of our application.</p>
</li>
</ul>
<p>In order to decide whether we are adding data to the current state or we should initialize it, we check for a property called <code>numLevels</code>. This is something that comes from the API, the very first time we establish the WebSocket connection.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-117.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Initial payload</em></p>
<p>The rest of the code you see in this <a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/main/src/components/OrderBook/index.tsx">file</a> is mostly for preparing and rendering the results on the screen.</p>
<p>The most interesting part would be the method <code>buildPriceLevels</code> that is used for both halves – bids and asks. It sorts the data, makes the necessary calculations, and passes it to the relevant components for visualizing it. Those are <code>DepthVisualizer</code> and <code>PriceLevelRow</code> I mentioned earlier in this article.</p>
<h2 id="heading-grouping">Grouping</h2>
<p>The grouping is an important part of how the order book works, as it defines by what ticket size the orders are grouped.</p>
<p>In our application, I have implemented a toggling functionality per each market, that allows grouping it as follows:</p>
<ul>
<li>Between 0.5, 1, 2.5 for XBTUSD market.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-118.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>XBTUSD market grouping</em></p>
<ul>
<li>Between 0.05, 0.1 and 0.25 for ETHUSD market.</li>
</ul>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-119.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>ETHUSD market grouping</em></p>
<p>There is a short gist I created when trying to figure out how to implement the grouping logic. You may find it <a target="_blank" href="https://gist.github.com/mihailgaberov/5faa2c1c3e4fd3e0593ad68861b989ce">here</a>.</p>
<p>Also, aside from that gist, while developing this I have performed more than a few experiments out of the project itself. And just because these are just local files on my computer, I will publish them here for those of you who are even more curious.</p>
<p>It’s a small side npm project that has only one dependency. Here is the package.json file:</p>
<pre><code class="lang-jsx">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"grouping"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-string">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-string">"license"</span>: <span class="hljs-string">"MIT"</span>,
  <span class="hljs-string">"dependencies"</span>: {
    <span class="hljs-string">"lodash.groupby"</span>: <span class="hljs-string">"^4.6.0"</span>
  }
}
</code></pre>
<p>And here is the code itself:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> bids = [
    [
        <span class="hljs-number">50163</span>,
        <span class="hljs-number">110</span>
    ],
    [
        <span class="hljs-number">50162</span>,
        <span class="hljs-number">13140</span>
    ],
    [
        <span class="hljs-number">50158</span>,
        <span class="hljs-number">3763</span>
    ],
    [
        <span class="hljs-number">50156</span>,
        <span class="hljs-number">1570</span>
    ],
    [
        <span class="hljs-number">50155</span>,
        <span class="hljs-number">21997</span>
    ],
    [
        <span class="hljs-number">50152.5</span>,
        <span class="hljs-number">450</span>
    ],
    [
        <span class="hljs-number">50151</span>,
        <span class="hljs-number">4669</span>
    ],
    [
        <span class="hljs-number">50150.5</span>,
        <span class="hljs-number">10329</span>
    ],
    [
        <span class="hljs-number">50150</span>,
        <span class="hljs-number">2500</span>
    ],
    [
        <span class="hljs-number">50149.5</span>,
        <span class="hljs-number">450</span>
    ],
    [
        <span class="hljs-number">50149</span>,
        <span class="hljs-number">4022</span>
    ],
    [
        <span class="hljs-number">50148</span>,
        <span class="hljs-number">20000</span>
    ],
    [
        <span class="hljs-number">50147</span>,
        <span class="hljs-number">5166</span>
    ],
    [
        <span class="hljs-number">50146.5</span>,
        <span class="hljs-number">5274</span>
    ],
    [
        <span class="hljs-number">50145</span>,
        <span class="hljs-number">174609</span>
    ],
    [
        <span class="hljs-number">50143</span>,
        <span class="hljs-number">20000</span>
    ],
    [
        <span class="hljs-number">50141</span>,
        <span class="hljs-number">28000</span>
    ],
    [
        <span class="hljs-number">50140.5</span>,
        <span class="hljs-number">5000</span>
    ],
    [
        <span class="hljs-number">50138</span>,
        <span class="hljs-number">6000</span>
    ],
    [
        <span class="hljs-number">50132.5</span>,
        <span class="hljs-number">4529</span>
    ],
    [
        <span class="hljs-number">50132</span>,
        <span class="hljs-number">4755</span>
    ],
    [
        <span class="hljs-number">50131</span>,
        <span class="hljs-number">12483</span>
    ],
    [
        <span class="hljs-number">50128.5</span>,
        <span class="hljs-number">61115</span>
    ],
    [
        <span class="hljs-number">50128</span>,
        <span class="hljs-number">23064</span>
    ],
    [
        <span class="hljs-number">50125.5</span>,
        <span class="hljs-number">181363</span>
    ]
]

<span class="hljs-comment">/* function roundDownNearest(num, acc) {
    if (acc &lt; 0) {
        return Math.floor(num * acc) / acc;
    } else {
        return Math.floor(num / acc) * acc;
    }
} */</span>

<span class="hljs-comment">/* function groupByTicketSize(ticketSize, levels) {
    const result = levels.map((element, idx) =&gt; {
        const nextLevel = levels[idx + 1];

        if (nextLevel) {
            const currentPrice = element[0];
            const currentSize = element[1];
            const nextPrice = nextLevel[0];
            const nextSize = nextLevel[1];
            console.log("current level: ", element)
            console.log("next level: ", nextLevel)

            element[0] = roundDownNearest(currentPrice, ticketSize);

            if (currentPrice - nextPrice &lt; ticketSize) {
                element[1] = currentSize + nextSize;
            }
            console.log("==================================&gt; Result: ", element)

            return element;
        }

    }).filter(Boolean); 


    console.log("============================================================");
    console.log(result)
} */</span>

<span class="hljs-keyword">const</span> test = [
    [<span class="hljs-number">1004.5</span>, <span class="hljs-number">1</span>],
    [<span class="hljs-number">1001.5</span>, <span class="hljs-number">1</span>],
    [<span class="hljs-number">1001</span>,   <span class="hljs-number">1</span>],
    [<span class="hljs-number">1000.5</span>, <span class="hljs-number">1</span>],
    [<span class="hljs-number">1000</span>,   <span class="hljs-number">1</span>],
    [<span class="hljs-number">999.5</span>,  <span class="hljs-number">1</span>],
    [<span class="hljs-number">999</span>,    <span class="hljs-number">1</span>],
    [<span class="hljs-number">990</span>,    <span class="hljs-number">1</span>],
    [<span class="hljs-number">988</span>,    <span class="hljs-number">1</span>]
]

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">groupByTicketSize</span>(<span class="hljs-params">ticketSize, levels</span>) </span>{
    <span class="hljs-keyword">const</span> result = [];

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; levels.length; i++) {
        <span class="hljs-built_in">console</span>.log(levels[i])
        <span class="hljs-keyword">const</span> prevLevel = levels[i<span class="hljs-number">-1</span>]
        <span class="hljs-keyword">const</span> level1 = levels[i]
        <span class="hljs-keyword">const</span> level2 = levels[i+<span class="hljs-number">1</span>]

        <span class="hljs-keyword">if</span> (prevLevel &amp;&amp; level1 &amp;&amp; level1[<span class="hljs-number">0</span>] - ticketSize === prevLevel) <span class="hljs-keyword">return</span>

        <span class="hljs-keyword">if</span> (level2 &amp;&amp; level1[<span class="hljs-number">0</span>] - level2[<span class="hljs-number">0</span>] &lt; ticketSize) {
            <span class="hljs-keyword">const</span> newLevel = [level2[<span class="hljs-number">0</span>], level1[<span class="hljs-number">1</span>] + level2[<span class="hljs-number">1</span>]];
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"newLevel"</span>, newLevel)
            result.push(newLevel);
        } <span class="hljs-keyword">else</span> {
            result.push(level1)
        }
    }

    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"============================================================"</span>);
    <span class="hljs-built_in">console</span>.log(result)
}

<span class="hljs-comment">// groupByTicketSize(1, bids);</span>
groupByTicketSize(<span class="hljs-number">1</span>, test);
</code></pre>
<h2 id="heading-how-to-perform-unit-tests-on-the-app">How to Perform Unit Tests on the App</h2>
<p>For performing unit testing I used the <a target="_blank" href="https://testing-library.com/docs/react-testing-library/intro/">react-testing-library</a>.</p>
<p>The main idea behind it that the developer should write tests only for what the user will see and interact with. There is no much point of testing implementation details.</p>
<p>💡 Imagine, just to give you an example, that you have implemented a list component that is just displaying lines of textual data. Say something like a todo list.</p>
<p>Then imagine that this data is coming from an API call in the shape of array. A data structure that you could easily iterate through via various methods – some sort of a loop cycle, such as for() or while(). Or you could use another more functional approach, say .map() method.</p>
<p>Now ask yourself – for the end user, the one that will just see the listed text data, does your implementation matter? As long as everything works as expected and in a good, performant way, the answer is ‘no, it does not’.</p>
<p>This is what your tests should reflect.</p>
<p>In the context of our Order Book application, each test file is located in the same directory as the implementation file. Most of the tests are short and self-explanatory, due to the fact that these are testing mostly rendering logic and only the <a target="_blank" href="https://en.wikipedia.org/wiki/Happy_path">happy path</a>.</p>
<p>For example let’s take a look at the button component tests below:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { render, screen } <span class="hljs-keyword">from</span> <span class="hljs-string">'@testing-library/react'</span>;
<span class="hljs-keyword">import</span> Button <span class="hljs-keyword">from</span> <span class="hljs-string">'./index'</span>;

test(<span class="hljs-string">'renders button with title'</span>, <span class="hljs-function">() =&gt;</span> {
  render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Button</span> <span class="hljs-attr">backgroundColor</span>=<span class="hljs-string">{</span>'<span class="hljs-attr">red</span>'} <span class="hljs-attr">callback</span>=<span class="hljs-string">{jest.fn}</span> <span class="hljs-attr">title</span>=<span class="hljs-string">{</span>'<span class="hljs-attr">Toggle</span>'} /&gt;</span></span>);
  <span class="hljs-keyword">const</span> btnElement = screen.getByText(<span class="hljs-regexp">/Toggle/i</span>);
  expect(btnElement).toBeInTheDocument();
});
</code></pre>
<p>It just verifies that the component is rendered properly and it displays what we expect the user to see. Which is the title <em>Toggle</em> in this case.</p>
<p>For testing the <a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/main/src/components/OrderBook/orderbookSlice.test.ts">reducers</a> I have used <a target="_blank" href="https://jestjs.io/">Jest</a>, as this is the only not visual part that we'll cover. These tests are also pretty simple and self-explanatory. I use them for testing whether the initial application state is in place and to see that adding price levels to that state works correctly.</p>
<h2 id="heading-how-to-deploy-the-app-to-vercel">How to Deploy the App to Vercel</h2>
<p>Finally – deployment time. 🎉</p>
<p>After finishing the development and testing our application, let’s put it live.</p>
<p>I used the <a target="_blank" href="https://vercel.com/">Vercel</a> platform for this purpose. They offer a pretty rich and easy to use interface as well as integrations for all famous source control platforms out there – including, of course, GitHub (where our application repo lives).</p>
<p>Assuming you have a GitHub account, what you need to do if you want to deploy it on your own is to login with it <a target="_blank" href="https://vercel.com/login">here</a>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-120.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Vercel login screen</em></p>
<p>Click on the <em>+New Project</em> button in the top right corner. Then import your Git repository using the provided options in the screen that opens. Here is how mine looks:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-121.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Vercel Import Git Repository screen</em></p>
<p>After importing the project, you will be able to do the actual deploy. When finished, Vercel will generate URLs for you to access your newly deployed app.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-122.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Vercel production deployment screen</em></p>
<p>And I think you will receive an email letting you know if your deployment was successful. That email also contains these URLs.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-123.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Vercel successful deployment email</em></p>
<p>Congratulations! 👏🏻</p>
<p>You now have your own <a target="_blank" href="https://orderbook-mihailgaberov.vercel.app/">Order Book application</a> up and running online.</p>
<h2 id="heading-how-to-add-a-build-badge-on-github">How to Add a Build Badge on GitHub</h2>
<p>This is not order book related, but I decided to share it with you here anyway. It’s about those small details that make the big picture somehow more complete and attractive.</p>
<p>Maybe some of you have wondered how can you get one of these so called <em>badges</em>?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-124.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here is the answer: <a target="_blank" href="https://shields.io/">https://shields.io/</a>.</p>
<p>You go to the <a target="_blank" href="https://shields.io/category/other">Other section</a> and find the GitHub Deployments option.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-125.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Then click on it and follow the instructions.</p>
<p>There is one more thing you need to do in order to have this fully functioning. You go to your GitHub repository → <a target="_blank" href="https://github.com/mihailgaberov/orderbook/actions">Actions</a> tab and create new workflow file. You may just go ahead and copy the content of <a target="_blank" href="https://github.com/mihailgaberov/orderbook/actions/runs/2143399541/workflow">mine from here</a>. Name it <em>main.yml</em>.</p>
<p>What this will do is run the jobs defined in that file. In our case this is just the build job which is basically spinning a new build and running the tests.</p>
<p>After completing this, you just need add the following lines to your <a target="_blank" href="https://github.com/mihailgaberov/orderbook/blob/main/README.md">README</a> file:</p>
<pre><code class="lang-markdown"><span class="xml"><span class="hljs-comment">&lt;!-- prettier-ignore-start --&gt;</span></span>
[<span class="hljs-string">![Tests</span>](<span class="hljs-link">&lt;https://github.com/mihailgaberov/orderbook/actions/workflows/main.yml/badge.svg&gt;</span>)](<span class="hljs-link">&lt;https://github.com/mihailgaberov/orderbook/actions/workflows/main.yml&gt;</span>)
[<span class="hljs-string">![Build Status</span>][<span class="hljs-symbol">build-badge</span>]][<span class="hljs-symbol">build</span>]

[<span class="hljs-symbol">build-badge</span>]: <span class="hljs-link">&lt;https://img.shields.io/github/deployments/mihailgaberov/orderbook/production?label=vercel&amp;logoColor=vercel&gt;</span>
[<span class="hljs-symbol">build</span>]: <span class="hljs-link">&lt;https://github.com/mihailgaberov/orderbook/deployments&gt;</span>
<span class="xml"><span class="hljs-comment">&lt;!-- prettier-ignore-end --&gt;</span></span>
</code></pre>
<p>💡 Don’t forget to put your own details in the URLs, that is your GitHub username and the name of your repository.</p>
<p>After pushing these changes you should see the badges displayed on your README: 🥳.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-126.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>GitHub badges</em></p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>If you are reading this from the beginning, I will name you a champion. 🍾</p>
<p>It has been a long trip, but hopefully interesting and fun to walk along with me!</p>
<p>Now it’s time to summarize what we have done here and try to extract some useful insights which will help us in our future development challenges.</p>
<p>I will layout below my opinion of what was the most challenging in building this application. And I will be even more eager to find out what is yours.</p>
<h3 id="heading-rendering-performance-1">Rendering Performance</h3>
<p>This really bit me in the beginning, when I was building the UI and was trying to implement the drawing of the price level rows.</p>
<p>I mentioned earlier how I have managed to solve it and I think this is going to be something I will remember for sure.</p>
<h3 id="heading-grouping-functionality">Grouping Functionality</h3>
<p>Implementing this was also kind of challenging because there were several factors I had to take into account. Because of the market we are in and the range I had to do the calculations in.</p>
<p>It took me a while to polish it (remember the side mini project and the gist I shared in the previous sections) and I still think it could be improved even more. Try switching between the markets and the grouping values multiple times and observe the results.</p>
<h3 id="heading-space-for-improvement">Space for Improvement</h3>
<p>One thing already mentioned is for sure the grouping. Which should also improve the visualizing of the red and green parts – they (almost) always should form a not ideal triangle.</p>
<p>If we try to look at the bigger picture, this order book application can be a part of a dashboard screen filled with other widgets as well, and they all can interact between them.</p>
<p>For example, changing the grouping of the order book to reflect on changing the views in the other widgets as well – say showing a market chart like this one below:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/04/image-127.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>I am not even mentioning adding new markets as an <em>improvement</em>, as it’s kinda clear. But this should be taken into account when building the functionality for the current markets, as to do it in a way that will be easily extendable. So that adding a new market to the order book be a trivial and quick task to do.</p>
<p>I think that's all from me.</p>
<p>Thanks for reading! 🙏</p>
<h2 id="heading-references">References</h2>
<p>Here are few links you might find useful to read:</p>
<p><a target="_blank" href="https://www.joshwcomeau.com/css/styled-components/">The styled-components Happy Path</a></p>
<p><a target="_blank" href="https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/#what-is-rendering">Blogged Answers: A (Mostly) Complete Guide to React Rendering Behavior</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Style Your React Apps with Less Code Using Tailwind CSS, Styled Components, and Twin Macro ]]>
                </title>
                <description>
                    <![CDATA[ By Ibrahima Ndaw Tailwind is a utility-first CSS framework for rapidly building custom designs. It can be used alone to style React Apps. However, it can be better combined with Styled Components. That combination brings the magic of Tailwind into CS... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-style-your-react-apps-with-less-code-using-tailwind-css-and-styled-components/</link>
                <guid isPermaLink="false">66d85026d592ae8435de718a</guid>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ styled-components ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tailwind ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 15 Apr 2020 10:45:33 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/04/cover-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ibrahima Ndaw</p>
<p>Tailwind is a utility-first CSS framework for rapidly building custom designs. It can be used alone to style React Apps. However, it can be better combined with Styled Components. That combination brings the magic of Tailwind into CSS-in-JS.</p>
<p>In this guide, we will build a form component without writing a single line of CSS using Tailwind CSS, Styled Components, and Twin Macro.</p>
<p>Let's dive in!</p>
<ul>
<li><a class="post-section-overview" href="#heading-why-use-it">Why use it?</a></li>
<li><a class="post-section-overview" href="#heading-setting-up">Setting up</a></li>
<li><a class="post-section-overview" href="#heading-configuring-tailwind-css">Configuring Tailwind CSS</a></li>
<li><a class="post-section-overview" href="#heading-tailwind-css-and-styled-components">Tailwind CSS and Styled Components</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
<li><a class="post-section-overview" href="#heading-resources">Resources</a></li>
</ul>
<h2 id="heading-why-use-it">Why use it?</h2>
<p>The "Why" is pretty legit and important, since we can use either Tailwind CSS or Styled Components. So why combine them and use both at the same time?</p>
<p>Well, Tailwind classes can be quite long, and it causes our components to have some readability issues. Maintaining them can be tough.</p>
<p>In the case of Styled Components, there is no problem except the fact that we have to write the style. It is not that problematic – but why should we write something that Tailwind already offers?</p>
<p>So it makes sense to use Tailwind CSS in combination with Styled Components. Tailwind CSS helps with utility classes, and Styled Components keeps our components clean with the help of CSS-in-JS.</p>
<h2 id="heading-setting-up">Setting up</h2>
<p>In this guide, we will build a simple form as an example. And to do so, we need a fresh React app.</p>
<p>So, let's run in the terminal the following command.</p>
<pre><code class="lang-shell">    npx create-react-app react-styled-tailwind
</code></pre>
<p>Next, structure your folder as follows:</p>
<pre><code>├── src
|  ├── App.js
|  ├── App.test.js
|  ├── assets
|  |  └── tailwind.css
|  ├── index.js
|  ├── serviceWorker.js
|  ├── setupTests.js
|  ├── tailwind.config.js
|  └── styles
|     └── index.js
├── babel.plugin.js
├── package.json
├── postcss.config.js
├── README.md
├── yarn-error.log
└── yarn.lock
</code></pre><p>I will explain each file as we progress, but for now, let's install the dependencies.</p>
<pre><code class="lang-shell">    yarn add -D tailwindcss twin.macro autoprefixer babel-plugin-macros postcss-cli
</code></pre>
<p>Next, install Styled Components by running this command:</p>
<pre><code class="lang-shell">    yarn add styled-components
</code></pre>
<p>Once these libraries are installed, we can now move to the configuration of Tailwind CSS</p>
<h2 id="heading-configuring-tailwind-css">Configuring Tailwind CSS</h2>
<p>To configure it, we have to manually add a config file or run the following command to generate a new one:</p>
<pre><code class="lang-shell">    npx tailwind init src/tailwind.config.js
</code></pre>
<p>Here, instead of generating the config file on the root directory, you have to put it on the <code>src</code> folder – otherwise an error will be thrown by Tailwind Macro.</p>
<p>And the generated file will look like this:</p>
<ul>
<li><code>tailwind.config.js</code></li>
</ul>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">theme</span>: {
    <span class="hljs-attr">extend</span>: {},
  },
  <span class="hljs-attr">variants</span>: {},
  <span class="hljs-attr">plugins</span>: [],
}
</code></pre>
<p>As you can see, the config file is "empty" since there is no configuration. For this tutorial, we don't need to configure anything here. But you can customize it to follow your needs or run the command with the <code>--full</code> option to get the complete Tailwind config.</p>
<p>Next, we need to create a new file <code>postcss.config.js</code> in the root directory.</p>
<ul>
<li><code>postcss.config.js</code></li>
</ul>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">plugins</span>: [
    <span class="hljs-built_in">require</span>(<span class="hljs-string">"tailwindcss"</span>)(<span class="hljs-string">"./src/tailwind.config.js"</span>),
    <span class="hljs-built_in">require</span>(<span class="hljs-string">"autoprefixer"</span>),
  ],
}
</code></pre>
<p>This configuration tells the <code>postcss.config.js</code> file to use the Tailwind CSS library and the <code>tailwind.config.js</code> file during compile-time. With the help of <code>autoprefixer</code> it tracks which properties need to be prefixed.</p>
<p>With that setup, we can now move to the <code>babel.plugin.js</code> file which helps to transform Tailwind classes into CSS-in-JS code.</p>
<ul>
<li><code>babel.plugin.js</code></li>
</ul>
<pre><code class="lang-js"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">tailwind</span>: {
    <span class="hljs-attr">plugins</span>: [<span class="hljs-string">"macros"</span>],
    <span class="hljs-attr">config</span>: <span class="hljs-string">"./src/tailwind.config.js"</span>,
    <span class="hljs-attr">format</span>: <span class="hljs-string">"auto"</span>,
  },
}
</code></pre>
<p>Later we will see in action what this file does. But for now, just keep in mind that it's the glue between Tailwind CSS and Styled Components.</p>
<p><em>There are just three last steps to do to complete the setup.</em></p>
<p><img src="https://media.giphy.com/media/tXL4FHPSnVJ0A/source.gif" alt="still" width="500" height="330" loading="lazy"></p>
<p>First, in the <code>tailwind.css</code> file, we need to import some utilities from the Tailwind library.</p>
<ul>
<li><code>src/assets/tailwind.css</code></li>
</ul>
<pre><code class="lang-css"><span class="hljs-keyword">@tailwind</span> base;

<span class="hljs-keyword">@tailwind</span> components;

<span class="hljs-keyword">@tailwind</span> utilities;
</code></pre>
<p>Here, as you can see, there is nothing fancy, just some imports that allow us to use Tailwind utility classes.</p>
<p>The second step is to connect our React App with Tailwind CSS.</p>
<ul>
<li><code>index.js</code></li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>
<span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">"react-dom"</span>
<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">"./App"</span>
<span class="hljs-keyword">import</span> <span class="hljs-string">"./assets/styles.css"</span>
<span class="hljs-keyword">import</span> * <span class="hljs-keyword">as</span> serviceWorker <span class="hljs-keyword">from</span> <span class="hljs-string">"./serviceWorker"</span>

ReactDOM.render(
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">React.StrictMode</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">React.StrictMode</span>&gt;</span></span>,
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"root"</span>)
)

serviceWorker.unregister()
</code></pre>
<p>Here, we import <code>assets/styles.css</code> which contains the CSS style. And later, we will tweak the default script a bit to build the CSS and add it to the <code>assets/styles.css</code> file during compile.</p>
<p>And last but not the least, we have to update the <code>package.json</code> file.</p>
<ul>
<li><code>package.json</code></li>
</ul>
<pre><code class="lang-js"><span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"build:css"</span>: <span class="hljs-string">"postcss src/assets/tailwind.css -o src/assets/styles.css"</span>,
    <span class="hljs-string">"watch:css"</span>: <span class="hljs-string">"postcss src/assets/tailwind.css -o src/assets/styles.css"</span>,
    <span class="hljs-string">"start"</span>: <span class="hljs-string">"npm run watch:css &amp; react-scripts start"</span>,
    <span class="hljs-string">"build"</span>: <span class="hljs-string">"npm run build:css react-scripts build"</span>,
    <span class="hljs-string">"test"</span>: <span class="hljs-string">"react-scripts test"</span>,
    <span class="hljs-string">"eject"</span>: <span class="hljs-string">"react-scripts eject"</span>
 }
</code></pre>
<p>These two scripts <code>build:css</code> and <code>watch:css</code> will respectively build the CSS and watch for changes and rebuild it if needed. And as I said earlier, the output file will be located in the <code>assets</code> folder.</p>
<p>With that change, we can now use Tailwind in our app. Let's now combine it with Styled Components.</p>
<h2 id="heading-tailwind-css-and-styled-components">Tailwind CSS and Styled Components</h2>
<p>Earlier, in our structure folder, we had a <code>styles</code> folder. It's time to tweak it with the following code.</p>
<ul>
<li><code>styles/index.js</code></li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">"styled-components"</span>
<span class="hljs-keyword">import</span> tw <span class="hljs-keyword">from</span> <span class="hljs-string">"twin.macro"</span>

<span class="hljs-keyword">const</span> StyledForm = styled.main.attrs({
  <span class="hljs-attr">className</span>: <span class="hljs-string">"flex flex-col h-screen justify-center items-center bg-gray-100"</span>,
})<span class="hljs-string">`
  &amp; {
    form {
      <span class="hljs-subst">${tw<span class="hljs-string">`bg-white text-center rounded py-8 px-5 shadow max-w-xs`</span>}</span>
    }
    input {
      <span class="hljs-subst">${tw<span class="hljs-string">`border-gray-300 mb-4 w-full border-solid border rounded py-2 px-4`</span>}</span>
    }
    button {
      <span class="hljs-subst">${tw<span class="hljs-string">`bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 border border-blue-700 rounded`</span>}</span>
    }
  }
`</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> StyledForm
</code></pre>
<p>We start by importing <code>tw</code> which allows us to use Tailwind classes in nested properties. It's perfectly fine to use the utility classes with the <code>className</code> attribute, but if you want to nest properties you have to use the <code>twin.macro</code> library.</p>
<p>This library will use the babel plugin macros config (<code>babel.plugin.js</code>) to transform the Tailwind CSS utility classes used by nested selectors into readable code that Styled Components can understand.</p>
<p>You can see in this example below how the transformation is done.</p>
<pre><code class="lang-js"><span class="hljs-comment">// input</span>
<span class="hljs-keyword">const</span> test = ${tw<span class="hljs-string">`text-center bg-red w-full`</span>}
<span class="hljs-comment">// output</span>
<span class="hljs-keyword">const</span> test = {
    <span class="hljs-attr">background</span>: <span class="hljs-string">'red'</span>,
    <span class="hljs-attr">textAlign</span>: <span class="hljs-string">'center'</span>,
    <span class="hljs-attr">width</span>: <span class="hljs-string">'100%'</span>
}
</code></pre>
<p>Great! Now that we have combined Tailwind with Styled Components, let's add the styled component to the <code>App.js</code> file.</p>
<ul>
<li><code>App.js</code></li>
</ul>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>
<span class="hljs-keyword">import</span> StyledForm <span class="hljs-keyword">from</span> <span class="hljs-string">"./styles"</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">StyledForm</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Full name"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Password"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Sign In<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">StyledForm</span>&gt;</span></span>
  )
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App
</code></pre>
<p>Here, we just imported the styled component and wrapped everything with it to make our form look nice.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/react-tailwind-form.png" alt="Image of React form styled with Tailwind" width="600" height="400" loading="lazy"></p>
<p>Great! You can already see how powerful this combination is. We have built a form component without writing a line of CSS and the component is still readable.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>There is a bit of hassle to set up Tailwind CSS. But once it's done and combined with CSS-in-JS, it's really powerful and flexible. This is partly because we can customize the <code>tailwind.config.js</code> file to follow our need or just write normal CSS as we usually do with Styled Components. It's definitely something to consider in your next React app.</p>
<p>Thanks for reading!</p>
<p>You can find the <a target="_blank" href="https://github.com/ibrahima92/react-styled-tailwind">Source Code here</a>.</p>
<p><a target="_blank" href="https://www.ibrahima-ndaw.com/">Read more of my articles</a></p>
<p><a target="_blank" href="https://ibrahima-ndaw.us5.list-manage.com/subscribe?u=8dedf5d07c7326802dd81a866&amp;id=5d7bcd5b75">Subscribe to my newsletter</a></p>
<p><a target="_blank" href="https://twitter.com/ibrahima92_">Follow me on twitter</a></p>
<h2 id="heading-resources">Resources</h2>
<p><a target="_blank" href="https://tailwindcss.com/docs/installation/">Tailwind CSS Docs</a></p>
<p><a target="_blank" href="https://nerdcave.com/tailwind-cheat-sheet">Tailwind CSS Cheat sheet</a></p>
<p><a target="_blank" href="https://github.com/ben-rogerson/twin.macro">Twin Macro Docs</a></p>
<p><a target="_blank" href="https://styled-components.com/docs">Styled Components Docs</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ React Native Styling: Styled Components, Flexbox Layouts, and More ]]>
                </title>
                <description>
                    <![CDATA[ React Native provides an API for creating stylesheets and styling your components: StyleSheet. import React, { Component } from 'react'; import { StyleSheet, View, Text } from 'react-native'; export default class App extends Component {   render () ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/react-native-styling-styled-components-flexbox-layouts-and-more/</link>
                <guid isPermaLink="false">66c35d73b8711219e1e72dcf</guid>
                
                    <category>
                        <![CDATA[ flexbox ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React Native ]]>
                    </category>
                
                    <category>
                        <![CDATA[ styled-components ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 12 Jan 2020 19:53:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9df2740569d1a4ca3a8a.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>React Native provides an API for creating stylesheets and styling your components: <a target="_blank" href="https://facebook.github.io/react-native/docs/stylesheet">StyleSheet</a>.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { StyleSheet, View, Text } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-native'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  render () {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">View</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Text</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.header}</span>&gt;</span>I am a header!<span class="hljs-tag">&lt;/<span class="hljs-name">Text</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Text</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.text}</span>&gt;</span>I am some blue text.<span class="hljs-tag">&lt;/<span class="hljs-name">Text</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">View</span>&gt;</span></span>
    );
  }
}

<span class="hljs-keyword">const</span> styles = StyleSheet.create({
  <span class="hljs-attr">header</span>: {
    <span class="hljs-attr">fontSize</span>: <span class="hljs-number">20</span>
  },
  <span class="hljs-attr">text</span>: {
    <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span>
  }
});
</code></pre>
<p>While regular CSS stylesheets aren’t valid, React Native’s superset of CSS is very similar to traditional CSS. </p>
<p>Many CSS properties (e.g. <code>color</code>, <code>height</code>, <code>top</code>, <code>right</code>, <code>bottom</code>, <code>left</code>) are the same in StyleSheet. Any CSS properties that have hyphens (e.g. <code>font-size</code>, <code>background-color</code>) must be changed to camelCase (e.g. <code>fontSize</code>, <code>backgroundColor</code>).</p>
<p>Not all CSS properties exist in StyleSheet. Since there is no true concept of hovering on mobile devices, CSS hover properties don’t exist in React Native. Instead, React Native provides <a target="_blank" href="https://facebook.github.io/react-native/docs/handling-touches#touchables">Touchable components</a> that respond to touch events.</p>
<p>Styles are also not inherited as they are in traditional CSS. In most cases, you must declare the style of each component.</p>
<h2 id="heading-flexbox-layouts">Flexbox Layouts</h2>
<p>React Native uses an implementation of <a target="_blank" href="https://facebook.github.io/react-native/docs/flexbox">flexbox</a> similar to the web standard. By default, items in the view will be set to <code>display: flex</code>.</p>
<p>If you do not want to use flexbox, you can also arrange React Native components via <code>relative</code> or <code>absolute</code> positioning.</p>
<p>Flexbox in React Native defaults to <code>flexDirection: column</code>, instead of <code>flex-direction: row</code> (web standard). The <code>column</code> value displays flexible items vertically, which accommodates mobile devices in portrait orientation.</p>
<p>To learn more about flexbox, visit <a target="_blank" href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">this detailed guide on CSS-Tricks</a> and a gamified learning approach with <a target="_blank" href="http://flexboxfroggy.com/">Flexbox Froggy</a>.</p>
<h2 id="heading-styled-components">Styled Components</h2>
<p>Including lots of styles in a file with a component isn’t always easy to maintain. Styled components can solve this issue.</p>
<p>For example, a Button component may be used in multiple places across an application. Copying and pasting the style object with each Button instance would be inefficient. Instead, create a reusable, styled Button component:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { Text, TouchableOpacity } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-native'</span>;

<span class="hljs-keyword">const</span> Button = <span class="hljs-function">(<span class="hljs-params">{ onPress, children }</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { buttonStyle, textStyle } = styles;
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">TouchableOpacity</span> <span class="hljs-attr">onPress</span>=<span class="hljs-string">{onPress}</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{buttonStyle}</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Text</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{textStyle}</span>&gt;</span>
        {children}
      <span class="hljs-tag">&lt;/<span class="hljs-name">Text</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">TouchableOpacity</span>&gt;</span></span>
  );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Button;

<span class="hljs-keyword">const</span> styles = {
  <span class="hljs-attr">textStyle</span>: {
    <span class="hljs-attr">alignSelf</span>: <span class="hljs-string">'center'</span>,
    <span class="hljs-attr">color</span>: <span class="hljs-string">'#336633'</span>,
    <span class="hljs-attr">fontSize</span>: <span class="hljs-number">16</span>,
    <span class="hljs-attr">fontWeight</span>: <span class="hljs-string">'600'</span>,
    <span class="hljs-attr">paddingTop</span>: <span class="hljs-number">10</span>,
    <span class="hljs-attr">paddingBottom</span>: <span class="hljs-number">10</span>
  },
  <span class="hljs-attr">buttonStyle</span>: {
    <span class="hljs-attr">backgroundColor</span>: <span class="hljs-string">'#fff'</span>,
    <span class="hljs-attr">borderWidth</span>: <span class="hljs-number">1</span>,
    <span class="hljs-attr">borderColor</span>: <span class="hljs-string">'#336633'</span>,
    <span class="hljs-attr">paddingTop</span>: <span class="hljs-number">4</span>,
    <span class="hljs-attr">paddingBottom</span>: <span class="hljs-number">4</span>,
    <span class="hljs-attr">paddingRight</span>: <span class="hljs-number">25</span>,
    <span class="hljs-attr">paddingLeft</span>: <span class="hljs-number">25</span>,
    <span class="hljs-attr">marginTop</span>: <span class="hljs-number">10</span>,
    <span class="hljs-attr">width</span>: <span class="hljs-number">300</span>
  }
};
</code></pre>
<p>The styled Button component can be easily imported and used across the application without repeatedly declaring the style object:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { TextInput, View } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-native'</span>;
<span class="hljs-keyword">import</span> Button <span class="hljs-keyword">from</span> <span class="hljs-string">'./styling/Button'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Login</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">View</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">TextInput</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Username or Email'</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">TextInput</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">'Password'</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">Button</span>&gt;</span>Log In<span class="hljs-tag">&lt;/<span class="hljs-name">Button</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">View</span>&gt;</span></span>
    );
  }
}
</code></pre>
<h2 id="heading-libraries-for-styling">Libraries for Styling</h2>
<p>There are a few popular libraries for styling React Native. Some of them provide features similar to <a target="_blank" href="https://guide.freecodecamp.org/bootstrap/index.md">Bootstrap</a>, including default forms, button styles, and page layout options. </p>
<p>One of the most popular libraries is <a target="_blank" href="https://github.com/styled-components/styled-components">styled-components</a>. There are many others you can find on npm and GitHub to try for yourself.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ You Don't Need CSS-in-JS: Why (and When) I Use Stylesheets Instead ]]>
                </title>
                <description>
                    <![CDATA[ CSS-in-JS is all the rage. But is it really the best option? Solving problems you don’t need to solve Don’t get me wrong, CSS-in-JS is a great solution, but it’s for a problem most people don’t have. Maintaining your components in a very siloed appro... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/you-dont-need-css-in-js-why-i-use-stylesheets/</link>
                <guid isPermaLink="false">66b8e3a668c5b9f37d1d1af3</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS in JS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Sass ]]>
                    </category>
                
                    <category>
                        <![CDATA[ styled-components ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Colby Fayock ]]>
                </dc:creator>
                <pubDate>Tue, 13 Aug 2019 14:30:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/08/you-dont-need-css-in-js.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>CSS-in-JS is all the rage. But is it really the best option?</p>
<h2 id="heading-solving-problems-you-dont-need-to-solve">Solving problems you don’t need to solve</h2>
<p>Don’t get me wrong, CSS-in-JS is a great solution, but it’s for a problem most people don’t have. Maintaining your components in a very siloed approach absolutely helps things like:</p>
<ul>
<li>Unintentional side effects of cascading styles</li>
<li>Helping teams organize their rules</li>
<li>Avoiding stepping on each other’s toes while developing</li>
</ul>
<p>But those really only become problems with large teams with many developers and a vast library of components.</p>
<h2 id="heading-so-what-do-you-want-me-to-use">So what do you want me to use?</h2>
<p>To start from a slightly higher point of view, you can get in the habit of a few basic ideas:</p>
<ul>
<li>Set and follow some basic rules for writing</li>
<li>Use tooling or set standards for organization</li>
<li>Developing with methodologies like <a target="_blank" href="http://getbem.com/">BEM</a></li>
</ul>
<p>This will eliminate any of those concerns on a smaller project (or large) and can actually make life easier.</p>
<h2 id="heading-what-css-in-js-is-good-at">What CSS-in-JS is good at…</h2>
<h3 id="heading-helping-large-teams-preserve-sanity">Helping large teams preserve sanity</h3>
<p>Part of why this solution exists is because very large teams have a hard time avoiding conflicts when they have a huge library to deal with. Being able to have your component and anything that impacts it in one compartmentalized area helps people avoid stepping on each other’s feet and potentially rolling out tweaks that unintentionally cascade throughout the app. This is great but more likely than not, you’re 1 of a few (or alone) working on a small app. If you and your team aren’t communicating about some basic rules and standards, I’d argue you have bigger problems.</p>
<h3 id="heading-kind-of-eliminates-the-need-to-learn-css-kind-of">Kind of eliminates the need to learn CSS (kind of)</h3>
<p>Some developers mock CSS saying it’s not real code, others are scared about it’s magic (don’t be, embrace it). Only having to worry about a few rules in one component helps put people’s mind at ease knowing it’s just a little more JS that changes how it looks a bit.</p>
<h2 id="heading-what-can-both-do">What can both do?</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/1_VRkx9H7RikKZg4pl6EP5rw.png" alt="Image" width="600" height="400" loading="lazy">
<em>CSS pointing at CSS</em></p>
<h3 id="heading-hot-module-reloading-hmr">Hot Module Reloading (HMR)</h3>
<p>Though some say an advantage to CSS-in-JS is HMR, you’ll find this works fine with stylesheets. Sometimes it actually works a little nicer if you’re working on a component that requires a rerender such as those with a network request as a dependency, where the CSS changes won’t force that rerender.</p>
<h3 id="heading-variables-global-settings">Variables, Global Settings</h3>
<p>If someone is making an argument that CSS can’t do that, it’s because they haven’t been paying attention for a while. Not only does Sass provide this, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties">it's native to modern browsers</a>.</p>
<h3 id="heading-encapsulation">Encapsulation</h3>
<p>Yes, you don’t need JS to do this. Add a class name to the top-level element of the component or page, nest all styles inside, and you have your encapsulation.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.page-about</span> {
  .header {
    <span class="hljs-attribute">background-color</span>: red;
  }
}

<span class="hljs-selector-class">.navigation</span> {
  .button {
    <span class="hljs-attribute">background-color</span>: blue;
  }
}
</code></pre>
<h3 id="heading-linting">Linting</h3>
<p><a target="_blank" href="https://stylelint.io/">https://stylelint.io/</a></p>
<h3 id="heading-a-lot-more">A lot more</h3>
<p>Honestly, there’s probably a lot more that both do similarly that you just don’t realize.</p>
<h2 id="heading-what-stylesheets-and-sass-do-better">What stylesheets and SASS do better…</h2>
<h3 id="heading-rule-sharing-and-configuration">Rule sharing and configuration</h3>
<p>SASS allows you to configure variables, custom functions, and mixins that take your CSS development to the next level.</p>
<p>Ignoring the bad selector names:</p>
<pre><code class="lang-css">// <span class="hljs-selector-tag">settings</span><span class="hljs-selector-class">.scss</span>

$<span class="hljs-selector-tag">color-ultraviolet</span>: <span class="hljs-selector-id">#5F4B8B</span>;

// <span class="hljs-selector-tag">colbys-styles</span><span class="hljs-selector-class">.scss</span>

<span class="hljs-keyword">@import</span> <span class="hljs-string">"settings"</span>;

<span class="hljs-selector-class">.colbys-text-color</span> {
  <span class="hljs-attribute">color</span>: $color-ultraviolet
}

<span class="hljs-selector-class">.colbys-background-color</span> {
  <span class="hljs-attribute">background-color</span>: $color-ultraviolet
}
</code></pre>
<p>While the syntax and configuration of this are arguably easier than setting up a bunch of object configurations in JS, this greatly allows you to provide consistent visual experiences and DRY up your code.</p>
<h3 id="heading-responsive-design">Responsive design</h3>
<p>One of the many things that add to the role of a good front end engineer is paying attention to how the project will look across multiple devices and sizes. Overall, UX is everyone’s job. Developing with a responsive-first mindset not only makes that process easier, it helps build a better product.</p>
<p>Trying to make your components responsive in JS means more Javascript and more event listeners. Not only does this add complexity, it hits performance. We can do this much easier with media queries baked right into CSS.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.colbys-sidebar</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
}

// <span class="hljs-selector-tag">NO</span> <span class="hljs-selector-tag">EVENT</span> <span class="hljs-selector-tag">LISTENERS</span>

<span class="hljs-keyword">@media</span> (<span class="hljs-attribute">min-width:</span> <span class="hljs-number">1024px</span>) {
  <span class="hljs-selector-class">.colbys-sidebar</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">25%</span>;
  }
}
</code></pre>
<p>Instead of having to throttle the event listeners, making sure your event listeners unregister on unmount, and just dealing with organizing that all in “the react way”, media queries trigger on-demand and will flip your styles as needed in a more consistent manner.</p>
<h3 id="heading-less-complexity-of-your-components">Less complexity of your components</h3>
<p>Being able to focus on the functionality and the rendered output allows you to avoid pulling in libraries or complex methods to essentially patch CSS into your JS, not to mention the JS hack or two or three that you’re using to get it working in the first place.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// This is an exaggeration</span>

<span class="hljs-keyword">const</span> styles = {
  <span class="hljs-attr">color</span>: blue;
}

<span class="hljs-keyword">if</span> ( whos_favorite === <span class="hljs-string">'Colby'</span> || whos_favorite === <span class="hljs-string">'Lord Commander'</span> ) {
  styles.color = <span class="hljs-string">'ultraviolet'</span>;
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> ( whos_favorite === <span class="hljs-string">'The Gary'</span> ) {
  styles.color = <span class="hljs-string">'red'</span>;
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> ( whos_favorite === <span class="hljs-string">'Mooncake'</span> ) {
  styles.color = <span class="hljs-string">'green'</span>;
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> ( whos_favorite === <span class="hljs-string">'HUE'</span> ) {
  styles.color = <span class="hljs-string">'blue'</span>;
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> ( whos_favorite === <span class="hljs-string">'KVN'</span> ) {
  styles.color = <span class="hljs-string">'yellow'</span>;
}

&lt;MyCompnent styles={styles} /&gt;
</code></pre>
<h3 id="heading-performance">Performance</h3>
<p><a target="_blank" href="https://medium.com/@addyosmani/the-cost-of-javascript-in-2018-7d8950fbb5d4">Less Javascript is always a win</a>. It’s less your browser has to load, less your browser has to compile, which will ultimately translate to quicker page speed. When the browser loads a page, it tries to optimize the HTML and CSS as much as possible. Yes, you probably are loading more CSS upfront, but more JS is very costly and also is more likely to <a target="_blank" href="https://developers.google.com/web/fundamentals/performance/rendering/">force a full rerender</a>;</p>
<p>A lot of the little magic bits you do with Javascript can be done with some pretty powerful CSS animation methods, just browse Codepen a bit or check out something like <a target="_blank" href="http://animista.net/">Animista</a>.</p>
<p>I don’t actually have any numbers on this aside <a target="_blank" href="https://blog.primehammer.com/the-performance-of-styled-react-components/">from a few good notes</a> and some <a target="_blank" href="https://github.com/A-gambit/CSS-IN-JS-Benchmarks">CSS-in-JS benchmarks</a>. <em>Has anyone done the legwork on this?</em></p>
<h2 id="heading-at-the-end-of-the-day-do-whats-effective">At the end of the day, do what’s effective</h2>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/1_rHuLBikidh3kSQ5M4JXjQQ.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong>Everyone has a personal preference, everyone is productive in a different way.</strong> Do what’s best for you, do what’s best for your team, and avoid treating what other developers say as dogmatic rights and wrongs.</p>
<p>If you’re a lone developer on a project and want to practice CSS-in-JS to get used to it for when you’re on a big team, go for it! If you’re on a huge, huge team at Facebook and want to use stylesheets, well you might run into issues if everyone’s not following the same guidelines, but do what’s best for you and your team.</p>
<p>The only way you can figure that out is with experience and experimentation. Play with both solutions and figure out why YOU think one is better than the other. You never know where you’ll end up after landing that gig at Google or your new startup in your garage.</p>
<div id="colbyfayock-author-card">
  <p>
    <a href="https://twitter.com/colbyfayock">
      <img src="https://res.cloudinary.com/fay/image/upload/w_2000,h_400,c_fill,q_auto,f_auto/w_1020,c_fit,co_rgb:007079,g_north_west,x_635,y_70,l_text:Source%20Sans%20Pro_64_line_spacing_-10_bold:Colby%20Fayock/w_1020,c_fit,co_rgb:383f43,g_west,x_635,y_6,l_text:Source%20Sans%20Pro_44_line_spacing_0_normal:Follow%20me%20for%20more%20JavaScript%252c%20UX%252c%20and%20other%20interesting%20things!/w_1020,c_fit,co_rgb:007079,g_south_west,x_635,y_70,l_text:Source%20Sans%20Pro_40_line_spacing_-10_semibold:colbyfayock.com/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_68,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_145,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_222,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/w_300,c_fit,co_rgb:7c848a,g_north_west,x_1725,y_295,l_text:Source%20Sans%20Pro_40_line_spacing_-10_normal:colbyfayock/v1/social-footer-card" alt="Follow me for more Javascript, UX, and other interesting things!" width="2000" height="400" loading="lazy">
    </a>
  </p>
  <ul>
    <li>
      <a href="https://twitter.com/colbyfayock">? Follow Me On Twitter</a>
    </li>
    <li>
      <a href="https://youtube.com/colbyfayock">?️ Subscribe To My Youtube</a>
    </li>
    <li>
      <a href="https://www.colbyfayock.com/newsletter/">✉️ Sign Up For My Newsletter</a>
    </li>
  </ul>
</div>

<p><em>Originally published at <a target="_blank" href="https://www.colbyfayock.com/2019/07/you-dont-need-css-in-js-why-i-use-stylesheets">https://www.colbyfayock.com/2019/07/you-dont-need-css-in-js-why-i-use-stylesheets</a>.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Styled Components: The Essentials Explained in 3 Steps ]]>
                </title>
                <description>
                    <![CDATA[ By Thomas Weibenfalk Cover Photo by Hello I’m Nik ?? on Unsplash I love React and Styled Components. It’s like building stuff with lego bricks into something bigger and whole. Styled Components are awesome and a perfect match for React. They really... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/styled-components-essentials-in-three-steps/</link>
                <guid isPermaLink="false">66d461513a8352b6c5a2ab1b</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ styled-components ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 12 Aug 2019 14:45:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/08/lego-1.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Thomas Weibenfalk</p>
<blockquote>
<p>Cover Photo by <a target="_blank" href="https://unsplash.com/@helloimnik?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Hello I’m Nik ??</a> on <a target="_blank" href="https://unsplash.com/search/photos/lego-part?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></p>
</blockquote>
<p>I love React and Styled Components. It’s like building stuff with lego bricks into something bigger and whole.</p>
<p>Styled Components are awesome and a perfect match for React. They really are. And they’re also easy to understand…really. </p>
<p>In this article I will break down everything you need to know to get started (and beyond started) in three parts. Not deeply technical, and simply explained. If you know these three things, you know enough to use Styled Components in your project without hassle.</p>
<p>The three things are:</p>
<ol>
<li><strong>How to create and use a Styled Component.</strong></li>
<li><strong>How to modify your CSS conditionally with props</strong></li>
<li><strong>How to create Global Styling.</strong></li>
</ol>
<p>I’ll go through them one by one now.</p>
<h1 id="heading-1-how-to-create-and-use-a-styled-component">1. How to create and use a Styled Component</h1>
<p>I’ll dive right into it. First you have to install Styled Components in your project. Do it by typing:</p>
<pre><code class="lang-js">npm i styled-components
</code></pre>
<p>Now you’re good to go. You can use Styled Components in your projects. Below is some code that I’ll explain below. Have a good look at it and continue reading below the code.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">"styled-components"</span>;

<span class="hljs-keyword">const</span> StyledLogin = styled.div<span class="hljs-string">`
  display: flex;
  align-items: center;
  flex-flow: column;
  width: 200px;
  height: 200px;
  margin: 0 auto;
  border: 2px solid #000;
  border-radius: 20px;
  background: #eee;

  h2 {
    font-family: Arial, Helvetica, sans-serif;
    font-size: 14px;
  }

  button {
    background: green;
    color: #fff;
    padding: 10px;
    margin: 5px;
    width: 150px;
    border: none;
    border-radius: 10px;
    box-sizing: border-box;
  }
`</span>;

<span class="hljs-keyword">const</span> StyledInput = styled.input<span class="hljs-string">`
  border: 1px solid #000;
  border-radius: 10px;
  padding: 10px;
  margin: 5px;
  width: 150px;
  box-sizing: border-box;
`</span>;

<span class="hljs-keyword">const</span> Login = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">StyledLogin</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">StyledInput</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"email"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">StyledInput</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"password"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">StyledLogin</span>&gt;</span></span>
);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Login;
</code></pre>
<p>The above code will create a component called Login that looks like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/login_1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Login form from the component Login.js</em></p>
<p>Nothing fancy, nothing special. Just a Login component to help us understand Styled Components better. Ok - the first thing you’ll notice in the above code is that we have to somehow tell React that we want to use Styled Components. We do this by importing it like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> “styled-components”;
</code></pre>
<p>Now we have imported an object called <code>styled</code> that we can use to style our components. This object has different properties that you can use depending on what you want to style. If it is a div, like in our example, you just simply access the div property on the <code>styled</code> object. Like so: <code>styled.div</code></p>
<p>If you want to style a button you can simply type <code>styled.button</code> instead.<br>Or if it was an h2 tag you can type <code>styled.h2</code> …you get the point!</p>
<p>These properties are holding functions that you can call with <em>tagged template literals</em>. Meaning that we can send in the data to these functions by using back-ticks and then put our CSS between these back-ticks (````). You also create a const to hold the Styled Component. So if we want to create a Styled Component for our Login component we just write the below code:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> StyledLogin = styled.div<span class="hljs-string">`
  display: flex;
  align-items: center;
  flex-flow: column;
  width: 200px;
  height: 200px;
  // And more CSS code below
`</span>;
</code></pre>
<p>In short, to create styling for a div element with Styled Components you just use this syntax:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> SomeName = styled.div<span class="hljs-string">` CSS code goes here … `</span>;
</code></pre>
<p>Then you can just use it as a regular component:</p>
<pre><code class="lang-js">&lt;SomeName&gt; Your other code here … &lt;/SomeName&gt;
</code></pre>
<p>You can create as many of these Styled Components as you need. In the above example I’ve created two Styled Components, one that’s called <code>StyledLogin</code> and one that’s called <code>StyledInput</code><strong>.</strong></p>
<p>One more thing about creating a standard Styled Component that’s good to know is the nesting part. Styled Components have the ability to nest styling just like you can do in, for example, SASS. </p>
<p>You can see in the above code that I have nested my styling for the <strong>h2</strong> and the <strong>button</strong> elements. This is great in so many ways! It will make your code a lot more structural and clean. You can easily see what styling belongs to what component. You are also isolating the styling to only that component, meaning that other <strong>h2</strong> and <strong>button</strong> elements in your App won’t be affected.</p>
<p>So, when it makes sense, use nesting to style elements. It doesn’t always make sense, though. You don’t have to create a completely new Styled Component for every little element. That’s when nesting like this come in handy instead.</p>
<p><em>That’s one</em> - <em>two to go.</em></p>
<h1 id="heading-2-how-to-modify-your-css-conditionally-with-props"><strong>2. How to modify your CSS conditionally with props.</strong></h1>
<p>Styled components can receive props. Just like a regular Component. By passing in props to your Styled Component you can do some conditional CSS styling. Smooooooth … ?‍♂️</p>
<p>Let’s say we want to change the color of the password input field depending on if the user typed in the wrong password or not.</p>
<p>Ok, I realize that this is a really simplified solution and there would be much more than a simple prop involved in stuff like this. But for the sake of this tutorial article, let’s say that we do it like this.</p>
<p>If we have a prop that’s called <code>correct</code> set to false, we make our textbox red instead. Let’s have a look at the below code. I’ve intentionally left out the styling code for the whole Login component to save space. So let’s pretend that that’s there and is the same as above.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> StyledInput = styled.input<span class="hljs-string">`
  border: 1px solid #000;
  border-radius: 10px;
  padding: 10px;
  margin: 5px;
  width: 150px;
  box-sizing: border-box;
  background: <span class="hljs-subst">${prop =&gt; prop.correct ? <span class="hljs-string">'white'</span> : <span class="hljs-string">'red'</span>}</span>;
`</span>;

<span class="hljs-keyword">const</span> Login = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">StyledLogin</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">StyledInput</span> <span class="hljs-attr">correct</span>=<span class="hljs-string">{true}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"email"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">StyledInput</span> <span class="hljs-attr">correct</span>=<span class="hljs-string">{false}</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"password"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Login<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">StyledLogin</span>&gt;</span></span>
);
</code></pre>
<p>This will give us this result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/login_2.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>First, take a look at the <code>Login</code> component. And the <code>StyledInput</code> components. I’ve created a prop that's called <code>correct</code> and I'm passing in <code>true</code> and <code>false</code> to the two different components. The one that gets the <em>true</em> value will be shown in white.<br>To access this prop value in your Styled Component CSS you can use the below code:</p>
<pre><code class="lang-js">background: ${<span class="hljs-function"><span class="hljs-params">prop</span> =&gt;</span> prop.correct ? ‘white’ : ‘red’};
</code></pre>
<p>You just simply create a ternary operator inside an arrow function surrounded by <code>${}</code> telling this Styled Component to select the white color if <code>prop.correct</code> is <code>false</code>. And use the red color if <code>prop.correct</code> is <code>true</code>. Simple as that!</p>
<p>You can do this with any CSS property you want! ✌️And that’s how you do conditional CSS with props in Styled Components.</p>
<p><em>Two down</em> - <em>one to go.</em></p>
<h1 id="heading-3-how-to-create-global-styling"><strong>3. How to create Global Styling.</strong></h1>
<p>The last essential thing you need to know to use Styled Components is how to create global styling.</p>
<p>Global styling is achieved by using a special function for this purpose from the Styled Components library. It’s called <code>createGlobalStyle</code> and you import it like this<strong>:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createGlobalStyle } <span class="hljs-keyword">from</span> ‘styled-components’;
</code></pre>
<p>Then you can create a Global Styled Component like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createGlobalStyle } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

<span class="hljs-keyword">const</span> GlobalStyle = createGlobalStyle<span class="hljs-string">`
  body {
    background: #000;
    color: #fff;
  }
`</span>;

<span class="hljs-keyword">const</span> App = <span class="hljs-function">() =&gt;</span> {
  <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">GlobalStyle</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Login</span> /&gt;</span>
  <span class="hljs-tag">&lt;/&gt;</span></span>
}
</code></pre>
<p>You just place the global style component at the top level of your application. Then, it will use the style throughout your App. In this case, I assume that the top-level Component is named <code>App</code>. You can also use props and do some conditional CSS in global Styled Components. Just like the regular Styled Components.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>That is it! There’s more to Styled Components than this, but I think that these really are the essentials that you need to know for using Styled Components. </p>
<p>If you’re interested in learning more I highly recommend that you go to the website <a target="_blank" href="https://www.styled-components.com/docs/">https://www.styled-components.com/docs/</a> and read the docs there.</p>
<p>Also, thank you for reading this post. I’m a Developer from Sweden that loves to teach and code. I also create courses on React and Gatsby online. You can find me on Udemy. Just search for Thomas Weibenfalk or hook me up on Twitter <strong>@weibenfalk</strong></p>
<p>I also have a Youtube channel were I teach free stuff, check it out <a target="_blank" href="https://www.youtube.com/channel/UCnnnWy4UTYN258FfVGeXBbg"><strong>here</strong></a><strong>.</strong></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Convert the Gatsby default starter to use styled-components ]]>
                </title>
                <description>
                    <![CDATA[ By Scott Spence Let's go through getting styled-components working with the Gatsby default starter. https://www.youtube.com/watch?v=O5sWySCr668 In this example we're going to use the Gatsby default starter you get with CodeSandbox and add in styled-c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/convert-the-gatsby-default-starter-to-use-styled-components-2018/</link>
                <guid isPermaLink="false">66d852209fbd5815f63ef038</guid>
                
                    <category>
                        <![CDATA[ Gatsby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ getting started ]]>
                    </category>
                
                    <category>
                        <![CDATA[ styled-components ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 29 Nov 2018 18:06:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/06/cover-3.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Scott Spence</p>
<p>Let's go through getting styled-components working with the Gatsby default starter.</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/O5sWySCr668" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
<p>In this example we're going to use the Gatsby default starter you get with <a target="_blank" href="https://codesandbox.io">CodeSandbox</a> and add in styled-components, so first up, open a <a target="_blank" href="https://codesandbox.io/s/">new CodeSandbox</a> and select Gatsby from the SERVER TEMPLATES.</p>
<h2 id="heading-1-dependencies">1. Dependencies</h2>
<p>In the dependencies section of the CodeSandbox editor you'll need to add the following:</p>
<pre><code class="lang-bash">gatsby-plugin-styled-components
styled-components
babel-plugin-styled-components
</code></pre>
<h2 id="heading-2-config">2. Config</h2>
<p>Now we need to change <code>gatsby-config.js</code> to incorporate the new dependencies we've just added. It doesn't have any configuration options so it can just go in as an extra line on the config, in this case I'm adding it after the <code>gatsby-plugin-sharp</code> plugin:</p>
<pre><code class="lang-js"><span class="hljs-string">'gatsby-transformer-sharp'</span>,
<span class="hljs-string">'gatsby-plugin-sharp'</span>,
<span class="hljs-string">'gatsby-plugin-styled-components'</span>,
</code></pre>
<p>Don't forget the comma at the end ?</p>
<h2 id="heading-3-global-style">3. Global Style</h2>
<p>Now that we're ready to rock n' roll with styled-components we need to remove the currently applied styled in the default starter and apply our own.</p>
<p>In the <code>src/components/layout.js</code> component there's an import for <code>layout.css</code> this is the CSS reset for the starter if we remove the import from here we'll see the styles for border and font be reset. We can now delete the <code>layout.css</code> file and create out own CSS reset using the <code>createGlobalStyle</code> function from styled-components.</p>
<p>Create a new folder <code>theme</code>, in this example it's in <code>src/theme</code> and add a <code>globalStyle.js</code> file in there.</p>
<p>This will export a <code>GlobalStyle</code> component for us to use throughout the app.</p>
<p>Let's add in a Google font and reset the <code>padding</code> and <code>margin</code>, for visual feedback we're going to add the font directly to the body element.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { createGlobalStyle } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> GlobalStyle = createGlobalStyle<span class="hljs-string">`
  @import url('https://fonts.googleapis.com/css?family=Kodchasan:400,700');
  body {
    padding: 0;
    margin: 0;
    font-family: Kodchasan;
  }
  a {
    text-decoration: none;
  }
  ul {
    margin: 0 auto;
    list-style-type: none;
  }
`</span>;
</code></pre>
<p>Ok, now we can use the export component here to apply styles globally in the app. So we need to have this as high up the component tree as possible, in this case that is in the <code>layout.js</code> component as it wraps all the pages in this project.</p>
<p>In <code>layout.js</code> import the <code>GlobalStyle</code> component.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> Header <span class="hljs-keyword">from</span> <span class="hljs-string">'./header'</span>;
<span class="hljs-keyword">import</span> { GlobalStyle } <span class="hljs-keyword">from</span> <span class="hljs-string">'../theme/globalStyle'</span>;
</code></pre>
<p>Then add it in with the other components being rendered.</p>
<pre><code class="lang-js">render={<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> (
  &lt;&gt;
    &lt;GlobalStyle /&gt;
    &lt;Helmet
    ...
</code></pre>
<p>Ok! Global styled applied, we should now see the font change and the margin around the body of the page change.</p>
<p>Time to use styled-components!</p>
<h2 id="heading-4-use-styled-components">4. Use styled-components</h2>
<p>Now let's convert all the inline styles used in the starter to styled-components.</p>
<p>This is the actual styling part, which is moving the existing styles to styled components, working from top to bottom of the file structure, changing:</p>
<pre><code>src/components/header.js
src/components/layout.js
src/pages/index.js
</code></pre><p><strong>header.js</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'gatsby'</span>;
<span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

<span class="hljs-keyword">const</span> HeaderWrapper = styled.div<span class="hljs-string">`
  background: rebeccapurple;
  margin-bottom: 1.45rem;
`</span>;

<span class="hljs-keyword">const</span> Headline = styled.div<span class="hljs-string">`
  margin: 0 auto;
  max-width: 960;
  padding: 1.45rem 1.0875rem;
  h1 {
    margin: 0;
  }
`</span>;

<span class="hljs-keyword">const</span> StyledLink = styled(Link)<span class="hljs-string">`
  color: white;
  textdecoration: none;
`</span>;

<span class="hljs-keyword">const</span> Header = <span class="hljs-function">(<span class="hljs-params">{ siteTitle }</span>) =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">HeaderWrapper</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Headline</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">StyledLink</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/"</span>&gt;</span>{siteTitle}<span class="hljs-tag">&lt;/<span class="hljs-name">StyledLink</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Headline</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">HeaderWrapper</span>&gt;</span></span>
);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Header;
</code></pre>
<p><strong>layout.js</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> PropTypes <span class="hljs-keyword">from</span> <span class="hljs-string">'prop-types'</span>;
<span class="hljs-keyword">import</span> Helmet <span class="hljs-keyword">from</span> <span class="hljs-string">'react-helmet'</span>;
<span class="hljs-keyword">import</span> { StaticQuery, graphql } <span class="hljs-keyword">from</span> <span class="hljs-string">'gatsby'</span>;

<span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

<span class="hljs-keyword">import</span> Header <span class="hljs-keyword">from</span> <span class="hljs-string">'./header'</span>;
<span class="hljs-keyword">import</span> { GlobalStyle } <span class="hljs-keyword">from</span> <span class="hljs-string">'../theme/globalStyle'</span>;

<span class="hljs-keyword">const</span> ContentWrapper = styled.div<span class="hljs-string">`
  margin: 0 auto;
  maxwidth: 960;
  padding: 0px 1.0875rem 1.45rem;
  paddingtop: 0;
`</span>;

<span class="hljs-keyword">const</span> Layout = <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">StaticQuery</span>
    <span class="hljs-attr">query</span>=<span class="hljs-string">{graphql</span>`
      <span class="hljs-attr">query</span> <span class="hljs-attr">SiteTitleQuery</span> {
        <span class="hljs-attr">site</span> {
          <span class="hljs-attr">siteMetadata</span> {
            <span class="hljs-attr">title</span>
          }
        }
      }
    `}
    <span class="hljs-attr">render</span>=<span class="hljs-string">{data</span> =&gt;</span> (
      <span class="hljs-tag">&lt;&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">GlobalStyle</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Helmet</span> <span class="hljs-attr">title</span>=<span class="hljs-string">{data.site.siteMetadata.title}</span> <span class="hljs-attr">meta</span>=<span class="hljs-string">{[{</span> <span class="hljs-attr">name:</span> '<span class="hljs-attr">description</span>', <span class="hljs-attr">content:</span> '<span class="hljs-attr">Sample</span>' }, { <span class="hljs-attr">name:</span> '<span class="hljs-attr">keywords</span>', <span class="hljs-attr">content:</span> '<span class="hljs-attr">sample</span>, <span class="hljs-attr">something</span>' }]}&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Helmet</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Header</span> <span class="hljs-attr">siteTitle</span>=<span class="hljs-string">{data.site.siteMetadata.title}</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">ContentWrapper</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">ContentWrapper</span>&gt;</span>
      <span class="hljs-tag">&lt;/&gt;</span></span>
    )}
  /&gt;
);

Layout.propTypes = {
  <span class="hljs-attr">children</span>: PropTypes.node.isRequired,
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Layout;
</code></pre>
<p><strong>index.js</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { Link } <span class="hljs-keyword">from</span> <span class="hljs-string">'gatsby'</span>;
<span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

<span class="hljs-keyword">import</span> Layout <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/layout'</span>;
<span class="hljs-keyword">import</span> Image <span class="hljs-keyword">from</span> <span class="hljs-string">'../components/image'</span>;

<span class="hljs-keyword">const</span> ImgWrapper = styled.div<span class="hljs-string">`
  max-width: 300px;
  margin-bottom: 1.45rem;
`</span>;

<span class="hljs-keyword">const</span> IndexPage = <span class="hljs-function">() =&gt;</span> (
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Layout</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hi people<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Welcome to your new Gatsby site.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Now go build something great.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ImgWrapper</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Image</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">ImgWrapper</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/page-2/"</span>&gt;</span>Go to page 2<span class="hljs-tag">&lt;/<span class="hljs-name">Link</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">Layout</span>&gt;</span></span>
);

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> IndexPage;
</code></pre>
<h2 id="heading-5-done">5. Done</h2>
<p><strong>Thanks for reading</strong></p>
<p>Here's the <a target="_blank" href="https://codesandbox.io/s/yp3z16yw11">example code</a> we worked on if you need reference. </p>
<blockquote>
<p><strong>You can read other articles like this on <a target="_blank" href="https://thelocalhost.blog/">my blog</a>.</strong></p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build A Debuggable Styled Component ]]>
                </title>
                <description>
                    <![CDATA[ By ChunLin Wu Styled-components is a CSS-In-JavaScript library. It allows you to write CSS code inside your React JSX files. Life is good when your component’s CSS properties can be dynamically changed with styled-components. However, there are some ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-debuggable-styled-component-10f7e4fbea2/</link>
                <guid isPermaLink="false">66c34f634f1fc448a3679041</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ styled-components ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 13 Sep 2018 14:39:55 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*OArsqiCwxTb78iN27XtVdg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By ChunLin Wu</p>
<p>Styled-components is a CSS-In-JavaScript library. It allows you to write CSS code inside your React JSX files. Life is good when your component’s CSS properties can be dynamically changed with styled-components.</p>
<p>However, there are some drawbacks when you try to debug your styled components. In this article, I’ll introduce to you the pros and cons of building components with traditional CSS and styled-components. Then, I’ll show you an easy method to overcome the flaws of building a styled component. Stay tuned!</p>
<h3 id="heading-getting-started">Getting started</h3>
<p>At first, let’s make a component with a conventional CSS file.</p>
<p>For now, the component looks like the image below.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*bMJr4IzslE0CGmTvCcT_jg.png" alt="Image" width="800" height="232" loading="lazy"></p>
<p>Pretty Cute huh!?</p>
<h3 id="heading-make-the-title-cute-puppy-another-color">Make the title “Cute Puppy” another color</h3>
<p>Let’s give the <code>Content.jsx</code> a prop. To make it simple, give it a prop called <strong>skyblue.</strong></p>
<p>Now, we can change <code>Content.jsx</code> CSS properties based on <code>skyblue</code><strong>.</strong> I want to introduce you to two methods to add new CSS properties via general CSS.</p>
<h4 id="heading-inline-style"><strong>Inline Style</strong></h4>
<p>As you can see, we take <code>skyblue</code> as the condition to add CSS properties to the style object. We then inject the style object as an inline style. Now the result will look like this…</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*heUmDWYNGBJjKDM7nc2kAA.png" alt="Image" width="800" height="236" loading="lazy"></p>
<p>The color of the title is now sky blue! Now let’s move on to the second method.</p>
<h4 id="heading-add-new-css-classes"><strong>Add New CSS Classes</strong></h4>
<p>As you know, we made a CSS class called <code>content--skyblue</code>. This is straightforward to make the color sky blue. We want to add this class to the title “Cute Puppy”. What we are doing is making an array to store CSS classes, then using the <code>join</code> method to split classes with space. So now, the className would be like<code>&lt;div className="content__title content--skyblue"&gt;Cute Puppy</code> . The result will also look the same as the inline-style method.</p>
<p>You can see that it’s not convenient to modify the styles with both of the methods above, especially for those complex UI components. You don’t want to write many condition statements to style your components, right?</p>
<p>So, what are the pros and cons of both <strong>inline-style</strong> and <strong>adding new CSS classes</strong>?</p>
<h4 id="heading-pros">Pros</h4>
<ol>
<li>It’s general CSS and vanilla JS — you don’t need to learn new syntax and API.</li>
<li>Easy to debug using browsers’ devtools.</li>
</ol>
<h4 id="heading-cons">Cons</h4>
<ol>
<li>It’s not flexible to modify inline-style because of <a target="_blank" href="http://muki.tw/wordpress/wp-content/uploads/2015/07/CSS-Specificity-full-710x1024.png">CSS specificity</a>. You cannot simply just add a class to override inline-style because inline-style has higher specificity.</li>
<li>It’s not clear to see what classes are included in <code>className</code> via the adding new CSS classes method. When you see this kind of code <code>&lt;div className={titleStyles.join(' ')}&gt;Cute Puppy</code> , you have to look back at the logic that you added to the classes. That will be a major drawback when you h<code>ave lots</code> of className to modify.</li>
</ol>
<p>That’s why I want to introduce you to <a target="_blank" href="https://www.styled-components.com/">styled-components</a>.</p>
<h3 id="heading-styled-components">Styled-components</h3>
<blockquote>
<p>Use the best bits of ES6 and CSS to style your apps without stress ?</p>
</blockquote>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*WI_n7M5OYeUh0SrkXZVGyw.png" alt="Image" width="800" height="801" loading="lazy">
<em>styled-components</em></p>
<p>Styled-components is a library which makes it easy to modify CSS properties. You can just install it via <code>npm install styled-components --save</code> or <code>yarn add styled-components</code>. Then you can use styled-components to style your components. Let’s take the Cute Puppy as the example.</p>
<p>At first, we need to import styled-components to our component. We import it as a name called <code>styled</code>. Then we can define what HTML element should be used for each styled-component. For example,</p>
<p><code>const Button = styled.button</code> /<em> CSS Properties </em>/ ``</p>
<p>means this Button component stands for the styled-component render a <code>&lt;button</code> /&gt;. Then we can simply move the CSS properties to each styled-component. That’s it! Just that simple! Now you can see the original version of Cute Puppy.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*bMJr4IzslE0CGmTvCcT_jg.png" alt="Image" width="800" height="232" loading="lazy"></p>
<p>How about changing the title’s color using styled-components? Styled-components take advantage of JavaScript ES6 <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals">template literals</a>. You can pass a function to template literals. That will be helpful when you want to modify CSS properties based on props. Let’s dive deeper into the topic via Cute Puppy.</p>
<p>We pass the prop <code>skyblue</code> to the <code>Title</code> component which was built with styled-components. Then we can simply pass a function to the CSS properties we want to modify via template literals. As you can see, we pass an arrow function <code>props =&gt; (props.skyblue ? 'skyblue' : 'blac</code>k')to determine under what condition should Title’s color be sky blue, and we just finish changing Title’s color!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*heUmDWYNGBJjKDM7nc2kAA.png" alt="Image" width="800" height="236" loading="lazy"></p>
<h3 id="heading-how-about-debugging">How About Debugging</h3>
<p>Let’s open Chrome Devtools to see what happens when we build a component with styled-components.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*McKlxIMuHFOWXY_tswRzDg.png" alt="Image" width="800" height="348" loading="lazy">
<em>What happened on Chrome Devtools</em></p>
<p>Styled-components have a built-in CSS module system. This is great for solving the problem of classnames conflict. However, we definitely don’t know what classes are we using when we try to debug on Chrome Devtools. Besides, when we check the render function in <code>Content.jsx</code>:</p>
<p>Do you know what HTML element we are using? absolutely not, right? You have to look back at each styled-component to check what HTML element is it using. That is annoying actually. Also, when you build styled-components in this way, basically you just abandon the powerful features of CSS selectors.</p>
<p>Considering the problems above, I want to introduce a simple method to build a debuggable styled-component, which combines general CSS with styled-components.</p>
<h3 id="heading-combine-css-selectors-with-styled-components">Combine CSS selectors with Styled-components</h3>
<p>At the beginning of this part, I want you to know how to <a target="_blank" href="https://www.styled-components.com/docs/basics#styling-any-components">style existing components with styled-components</a>.</p>
<blockquote>
<p>The styled method works perfectly on all of your own or any third-party components as well. As long as they pass the className prop to their rendered sub-components, which should pass it too, and so on. Ultimately, the className must be passed down the line to an actual DOM node for the styling to take any effect.</p>
</blockquote>
<p>We need to add <strong>className</strong> to general components and we can style them easily with styled-components. Let’s see how to take advantage of it to build a debuggable styled-component.</p>
<p>We need to wrap <code>Content.jsx</code> via the <strong>className</strong> prop and we can style it with this pattern:</p>
<p><code>const StyledContent = styled(Content)</code> /<em> CSS Properties </em>/ ``</p>
<p>Then we can wrap any component into the styled-component. In addition, we can also use the power of CSS selectors inside the styled-component. Even more, SCSS syntax is available in styled-components! Let’s see how it happens when we open the console in Chrome Devtools.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*aUt6gsRAGgRr_ewJ6c_E8w.png" alt="Image" width="800" height="352" loading="lazy"></p>
<p>Now the classes are meaningful, right? And we still benefit from the built-in CSS module system because of the className prop. To put it simply, you just need to take care of CSS classnames inside the component, then you will be fine ?. Remember how we modify CSS properties via passing a function to styled-components? It still works with this method! Of course, the result will still look like…</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*heUmDWYNGBJjKDM7nc2kAA.png" alt="Image" width="800" height="236" loading="lazy"></p>
<p>Life has never been so beautiful!</p>
<h3 id="heading-wrap-up">Wrap up</h3>
<p>We have gone through two methods to style component via traditional CSS. Then we learned how to style components easily with styled-components. In the end, we combined CSS selectors with styled-components. Now components can be easily styled and are also debuggable.</p>
<p>If you want to try out styled-components to style your components, but feel the pain when debugging, I would recommend that you give this method a try.</p>
<h3 id="heading-demohttpschun-lingithubiodebuggable-styled-components-example"><a target="_blank" href="https://chun-lin.github.io/Debuggable-Styled-Components-Example/">DEMO</a></h3>
<h3 id="heading-source-code">Source Code</h3>
<p>You can check the source code of every method on my Github repo</p>
<ol>
<li><p><a target="_blank" href="https://github.com/Chun-Lin/Debuggable-Styled-Components-Example/tree/general-css-version">Inline-Style</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/Chun-Lin/Debuggable-Styled-Components-Example/tree/general-css-version">Add a New Class</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/Chun-Lin/Debuggable-Styled-Components-Example/tree/styled-components-version">Styled-components</a></p>
</li>
<li><p><a target="_blank" href="https://github.com/Chun-Lin/Debuggable-Styled-Components-Example/tree/styled-components-css-selectors">Combine CSS Selectors with styled-components</a></p>
</li>
</ol>
<p>Thank you for reading my article. I hope it didn’t waste your time. If you like this article, please feel free to give me a clap ???. Your claps will motivate me to write more high-quality articles ✍️.</p>
<p>Follow me on <a target="_blank" href="https://twitter.com/wulin40063">Twitter</a></p>
<p>Follow me on <a target="_blank" href="https://github.com/Chun-Lin">Github</a></p>
<p>Connect me on <a target="_blank" href="https://www.linkedin.com/in/chunlin-wu-4114809b/">LinkedIn</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ styled-components ? getting started ]]>
                </title>
                <description>
                    <![CDATA[ By Scott Spence We're going to style the basic create react app with styled-components to look something like this: But first, preamble✨: I have always struggled with styling sites, it seems to be an aspect of starting web development that is either... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/styled-components-getting-started-2018/</link>
                <guid isPermaLink="false">66d852329fbd5815f63ef03e</guid>
                
                    <category>
                        <![CDATA[ getting started ]]>
                    </category>
                
                    <category>
                        <![CDATA[ styled-components ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 03 Apr 2018 16:44:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/06/ezgif.com-gif-maker.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Scott Spence</p>
<p>We're going to style the basic create react app with styled-components to look something like this:</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/5dwv10zpqa13wb4pr47l.gif" alt="Image" width="730" height="672" loading="lazy"></p>
<p>But first, preamble✨: I have always struggled with styling sites, it seems to be an aspect of starting web development that is either an afterthought or glossed over. Up until December last year I didn't really like styling anything at all with CSS, it was a chore rather than something I enjoyed doing.</p>
<p>This was until I started using styled-components, when I joined a build to learn project for a <a target="_blank" href="https://medium.com/chingu">Chingu</a> voyage (<a target="_blank" href="https://github.com/chingu-voyage3/grad.then/"><code>grad.then()</code></a> if you're interested) we decided to use a CSS-in-JS package, <a target="_blank" href="https://twitter.com/mar_biletska">Marina</a> who was on my team was such an inspiration for me watching how components were styled and really gave me the confidence to start using styled-components.</p>
<h6 id="heading-me-with-css-before">me with css before</h6>
<p><img src="https://media.giphy.com/media/2rj8VysAig8QE/giphy.gif" alt="Image" width="557" height="413" loading="lazy"></p>
<p>I want to share what I have learned so far by going through styling a basic react application.</p>
<p>There's some basic CSS concepts in this post that I was not aware of before starting out with styled-components that I presume are assumed in styling web pages.</p>
<p>Styling the body element of a site is assumed, so for when you are starting out with a blank canvas there are some defaults for all modern web browsers you add to your site, like leaving font size at 16px (or 1rem) or <code>box-sizing:</code> <code>border-box;</code> there's some packages out there to take care of this for you as well.</p>
<h3 id="heading-install-styled-components">Install styled-components</h3>
<p>Ok let's bootstrap the basic react application you get when using <a target="_blank" href="https://github.com/facebook/create-react-app#create-react-app-">Create React App</a> with <a target="_blank" href="https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b"><code>npx</code></a>, if you already have Create React App installed globally then you can use the command without <code>npx</code>.</p>
<pre><code class="lang-bash">npx create-react-app style-with-styled-components
<span class="hljs-built_in">cd</span> style-with-styled-components/
npm i styled-components
</code></pre>
<p>Ok, now we have the basic app we can style, thankfully <a target="_blank" href="https://github.com/gaearon">Dan</a> has kindly provided the starting styles for us so let's begin my using them with styled-components.</p>
<p>The way the CRA CSS is laid out, assumes that you will have a corresponding CSS file for each component, which can help with maintaining the CSS and lends to the React idea of having all your files separated into their component parts.</p>
<p>We can start with the <code>App.js</code> file and it's accompanying <code>App.css</code> file. Let's take a look at the <code>App.js</code> first:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> logo <span class="hljs-keyword">from</span> <span class="hljs-string">'./logo.svg'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-header"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{logo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-logo"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"logo"</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-title"</span>&gt;</span>Welcome to React<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-intro"</span>&gt;</span>
          To get started, edit <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>src/App.js<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> and save to reload.
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>In styled-components we'd create components for each of these elements that replace the aforementioned <code>className</code>'s. Ok we can start by migrating our styles into components, let's do one component first to get an idea of where we're going with this.</p>
<p>First, import <code>styled</code> into the <code>App.js</code> module:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;
</code></pre>
<p>Now let's look at <code>&lt;div className="App"&gt;</code>, it's the top level div for this component and is what I like to call the wrapper for the component. So let's give it an imaginative name AppWrapper.</p>
<p>Referring to the App.css there is <code>text-align: center;</code> which belongs to this, so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> AppWrapper = styled.div<span class="hljs-string">`
  text-align: center;
`</span>;
</code></pre>
<p>So here we have defined the <code>AppWrapper</code> const as a <code>styled.div</code> followed by back ticks inside of the back ticks we can write any regular CSS with the exact same CSS syntax you wold in a normal <code>.css</code> file.</p>
<p>Now that we have our <code>AppWrapper</code> we can replace the top level div on the <code>App.js</code> component.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;
<span class="hljs-keyword">import</span> logo <span class="hljs-keyword">from</span> <span class="hljs-string">'./logo.svg'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./App.css'</span>;
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AppWrapper</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">header</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-header"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{logo}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-logo"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"logo"</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-title"</span>&gt;</span>Welcome to React<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"App-intro"</span>&gt;</span>
          To get started, edit <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>src/App.js<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> and save to reload.
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">AppWrapper</span>&gt;</span></span>
    );
  }
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h3 id="heading-styled-components-all-the-things">styled-components all the things</h3>
<p>So let's do that for the remaining four CSS classes, and take a look, I'll define them underneath the <code>AppWrapper</code> here:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> rotate360 = keyframes<span class="hljs-string">`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
`</span>;
<span class="hljs-keyword">const</span> AppLogo = styled.img<span class="hljs-string">`
  animation: <span class="hljs-subst">${rotate360}</span> infinite 120s linear;
  height: 80px;
`</span>;
<span class="hljs-keyword">const</span> AppHeader = styled.div<span class="hljs-string">`
  background-color: #222;
  height: 150px;
  padding: 20px;
  color: white;
`</span>;
<span class="hljs-keyword">const</span> AppTitle = styled.h1<span class="hljs-string">`
  font-size: 1.3em;
`</span>;
<span class="hljs-keyword">const</span> AppIntro = styled.p<span class="hljs-string">`
  font-size: large;
`</span>;
</code></pre>
<p>So first off we've created a variable for the React svg <a target="_blank" href="https://www.styled-components.com/docs/basics#animations">animation</a>, you'll need to import the <code>keyframes</code> helper from styled-components like so:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> styled, { keyframes } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;
</code></pre>
<p>this can now be used throughout the <code>App.js</code> component and we can add an on <code>hover</code> selector to any of our styled-components within this module. Here we're going to add it to the <code>AppLogo</code> to keep the super sweet rotating React logo.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> AppLogo = styled.img<span class="hljs-string">`
  animation: <span class="hljs-subst">${rotate360}</span> infinite 120s linear;
  height: 80px;
  &amp;:hover {
    animation: <span class="hljs-subst">${rotate360}</span> infinite 1.5s linear;
  }
`</span>;
</code></pre>
<p>Ok, our app shouldn't look any different as we haven't added in our styled-components to the app <code>render()</code> method, so let's do that now.</p>
<p>Let's also change the intro text. You can add a wrapper for the <code>&lt;code&gt;</code> tags something like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> CodeWrapper = styled.code<span class="hljs-string">`
  font-size: 1.3rem;
`</span>;
</code></pre>
<p>But if you prefer you can nest selectors within the component, like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> AppIntro = styled.p<span class="hljs-string">`
  color: <span class="hljs-subst">${props =&gt; props.theme.dark}</span>;
  font-size: large;
  code {
    font-size: 1.3rem;
  }
`</span>;
</code></pre>
<p>Let's have a look at the <code>render()</code> method now…</p>
<pre><code class="lang-js">render() {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AppWrapper</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">AppHeader</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AppLogo</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{logo}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"logo"</span> /&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AppTitle</span>&gt;</span>Welcome to React<span class="hljs-tag">&lt;/<span class="hljs-name">AppTitle</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">AppHeader</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">AppIntro</span>&gt;</span>
        Bootstrapped with <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>create-react-app<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span>.
      <span class="hljs-tag">&lt;/<span class="hljs-name">AppIntro</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">AppIntro</span>&gt;</span>
        Components styled with <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>styled-components<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span>{' '}
        <span class="hljs-tag">&lt;<span class="hljs-name">EmojiWrapper</span> <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"nail polish"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">EmojiWrapper</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">AppIntro</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">AppWrapper</span>&gt;</span></span>
  )
}
</code></pre>
<p>Now all the classes originally used in <code>App.js</code> have been replaced so there's no need for the <code>import './App.css'</code> mapping, remove that aaaaand! Still no change!! Which is a good thing because at the moment we're swapping out the <code>.css</code> files for styled-components.</p>
<p>Cool, we have now replaced all the css with styled-components, now we can take a look at <code>injectGlobal</code>.</p>
<p>Let's take a look at how the <code>App.js</code> file should look before we move on:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> styled, { keyframes } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;
<span class="hljs-keyword">import</span> logo <span class="hljs-keyword">from</span> <span class="hljs-string">'./logo.svg'</span>;

<span class="hljs-keyword">const</span> AppWrapper = styled.div<span class="hljs-string">`
  text-align: center;
`</span>;

<span class="hljs-keyword">const</span> rotate360 = keyframes<span class="hljs-string">`
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
`</span>;

<span class="hljs-keyword">const</span> AppLogo = styled.img<span class="hljs-string">`
  animation: <span class="hljs-subst">${rotate360}</span> infinite 120s linear;
  height: 80px;
  &amp;:hover {
    animation: <span class="hljs-subst">${rotate360}</span> infinite 1.5s linear;
  }
`</span>;

<span class="hljs-keyword">const</span> AppHeader = styled.div<span class="hljs-string">`
  background-color: #222;
  height: 12rem;
  padding: 1rem;
  color: white;
`</span>;

<span class="hljs-keyword">const</span> AppTitle = styled.h1<span class="hljs-string">`
  font-weight: 900;
`</span>;

<span class="hljs-keyword">const</span> AppIntro = styled.p<span class="hljs-string">`
  font-size: large;
  code {
    font-size: 1.3rem;
  }
`</span>;

<span class="hljs-keyword">const</span> EmojiWrapper = styled.span.attrs({
  <span class="hljs-attr">role</span>: <span class="hljs-string">'img'</span>,
})<span class="hljs-string">``</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AppWrapper</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AppHeader</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">AppLogo</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{logo}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"logo"</span> /&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">AppTitle</span>&gt;</span>Welcome to React<span class="hljs-tag">&lt;/<span class="hljs-name">AppTitle</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">AppHeader</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AppIntro</span>&gt;</span>
          Bootstrapped with <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>create-react-app<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span>.
        <span class="hljs-tag">&lt;/<span class="hljs-name">AppIntro</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AppIntro</span>&gt;</span>
          Components styled with <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>styled-components<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">EmojiWrapper</span> <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"nail polish"</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">AppIntro</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">AppWrapper</span>&gt;</span></span>
    );
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<h3 id="heading-style-the-body-with-injectglobal">Style the body with injectGlobal</h3>
<p>For styling the body of our react app we currently have the <code>index.css</code> file that is being imported into the mounting point of our app in the <code>index.js</code> file.</p>
<p>To style the body we can use <a target="_blank" href="https://www.styled-components.com/docs/api#injectglobal"><code>injectGlobal</code></a> from styled-components which adds the styles directly to the stylesheet.</p>
<p>To do this you bring in the <code>injectGolabl</code> named export from styled-components and add your styles between the back ticks.</p>
<p>The current <code>index.css</code> looks like this:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-family</span>: sans-serif;
}
</code></pre>
<p>Let's add a <code>theme</code> folder in the <code>src</code> directory and add a <code>globalStyle.js</code> file where we can keep all our styles we want to use throughout the app, keeping the styles on one place will make changes simpler.</p>
<p>In <code>src/theme/globalStyle.js</code> we'll need to import the <code>injectGlobal</code> named export from styled-components and add the <code>index.css</code> styles into it:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> { injectGlobal } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

injectGlobal<span class="hljs-string">`
  body {
    padding: 0;
    margin: 0;
    font-family: sans-serif;
  }
`</span>;
</code></pre>
<p>Ok, now we're adding the body style to the stylesheet directly so there is no need for the <code>index.css</code> file mapping that is in <code>index.js</code> it should look like this now:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span> <span class="hljs-keyword">import</span> ReactDOM <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom'</span>

<span class="hljs-keyword">import</span> App <span class="hljs-keyword">from</span> <span class="hljs-string">'./App'</span>

<span class="hljs-keyword">import</span> registerServiceWorker <span class="hljs-keyword">from</span> <span class="hljs-string">'./registerServiceWorker'</span>

ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>))

registerServiceWorker()
</code></pre>
<p>We should still have our nice <code>sans-serif</code> font going on, but let's add in some nice Roboto for the body and Montserrat for the heading in our <code>globalStyle.js</code> module. We can import Google fonts with an <code>@import</code> in <code>injectGlobal</code> and apply Roboto to the body:</p>
<pre><code class="lang-js">injectGlobal<span class="hljs-string">`
  @import url(‘https://fonts.googleapis.com/css?family=Montserrat|Roboto');

  body {
    padding: 0;
    margin: 0;
    font-family: Roboto, sans-serif;
  }
`</span>;
</code></pre>
<p>Cool now we can add our imported font for or app header, and there's the option if we want all our <code>&lt;h1&gt;</code>'s to use the same font we can add that to the injectGlobal in our <code>globalStyle.js</code> module.</p>
<pre><code class="lang-js">injectGlobal<span class="hljs-string">`
  @import url(‘https://fonts.googleapis.com/css?family=Montserrat:400,900|Roboto');
  body {
    padding: 0;
    margin: 0;
    font-family: Roboto, sans-serif;
  }
  h1 {
    font-family: Montserrat;
  }
`</span>;
</code></pre>
<p>Then we can adjust the weight on the <code>AppTitle</code> component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> AppTitle = styled.h1<span class="hljs-string">`
  font-weight: 900;
`</span>;
</code></pre>
<p>To add the additional styles for fonts like Montserrat and Roboto you can specify them in the <code>@import url()</code> you'll notice that Montserrat has <code>:400,900</code> after it that is specifying the styles regular (400) and black (900), you can import as many as you like from Google fonts (CDN) but the more you import the longer it will take to load them, if you have a lot of fonts and styles you want in your app then consider adding them to a folder in the project, like:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> Montserrat <span class="hljs-keyword">from</span> <span class="hljs-string">'./fonts/Montserrat-Regular.ttf'</span>;

injectGlobal<span class="hljs-string">`@font-face { font-family: Montserrat; src: url(<span class="hljs-subst">${Montserrat}</span>); }`</span>;
</code></pre>
<h3 id="heading-theming">Theming</h3>
<p>Themes are often used to change the look and feel of a wide range of things at once. For example, you may have a night and day mode like in Twitter. You can create your own themes in styled-components too.</p>
<p><img src="https://thepracticaldev.s3.amazonaws.com/i/gwn8czgagns1n1545zgn.png" alt="Image" width="800" height="572" loading="lazy"></p>
<h3 id="heading-use-the-styled-components-themeprovider">Use the styled-components ThemeProvider</h3>
<p>Now say we want to have several components in our app that use a CSS colour property <code>color: #6e27c5</code> instead of hard coding it through the app for every component that uses it we can use the styled-components <code>ThemeProvider</code>.</p>
<p>For this we will need to import the <code>ThemeProvider</code> named export from styled-components, then define a <code>theme</code> object where our colour is going to live:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> theme = {
  <span class="hljs-attr">primary</span>: <span class="hljs-string">'#6e27c5'</span>,
};
</code></pre>
<p>Let's add the newly created <code>theme</code> to the <code>globalStyle</code> module we created previously.</p>
<p>To make the theme object available throughout the app component we'll wrap our app component in the <code>ThemeProvider</code> and import our awesome theme for use in the <code>ThemeProvider</code>:</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> styled, { keyframes, ThemeProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;
<span class="hljs-keyword">import</span> logo <span class="hljs-keyword">from</span> <span class="hljs-string">'./logo.svg'</span>;
<span class="hljs-keyword">import</span> { theme } <span class="hljs-keyword">from</span> <span class="hljs-string">'./theme/globalStyle'</span>;

<span class="hljs-comment">// our styled-components</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeProvider</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{theme}</span>&gt;</span>{/* all children can access the theme object */}<span class="hljs-tag">&lt;/<span class="hljs-name">ThemeProvider</span>&gt;</span></span>;
  }
}
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>Now the <code>theme</code> properties can be used as props in our styled-components, let's change the <code>background-color:</code> in the <code>AppHeader</code> component, whilst we're at it let's add a <code>dark: #222</code> property to our <code>theme</code> object and use that for the <code>color</code> property:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> AppHeader = styled.div<span class="hljs-string">`
  height: 12rem;
  padding: 1rem;
  color: <span class="hljs-subst">${props =&gt; props.theme.dark}</span>;
  background-color: <span class="hljs-subst">${props =&gt; props.theme.primary}</span>;
`</span>;
</code></pre>
<p>Now we can change our app theme globally</p>
<h3 id="heading-ok-cool-can-you-change-theme">Ok cool, can you change theme?</h3>
<p>This is what I was thinking and it turns out you can, there's a great <a target="_blank" href="https://stackoverflow.com/a/42899979/1138354">Stack Overflow answer</a> from <a target="_blank" href="https://twitter.com/mxstbr">Max</a> on it.</p>
<p>It got me thinking if you can switch between themes rather than define them for different sections like in the SO answer.</p>
<p>I started off by defining two themes (with imaginative names) in the <code>globalStyle.js</code> module:</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> theme1 = {
  <span class="hljs-attr">primary</span>: <span class="hljs-string">'#ff0198'</span>,
  <span class="hljs-attr">secondary</span>: <span class="hljs-string">'#01c1d6'</span>,
  <span class="hljs-attr">danger</span>: <span class="hljs-string">'#eb238e'</span>,
  <span class="hljs-attr">light</span>: <span class="hljs-string">'#f4f4f4'</span>,
  <span class="hljs-attr">dark</span>: <span class="hljs-string">'#222'</span>,
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> theme2 = {
  <span class="hljs-attr">primary</span>: <span class="hljs-string">'#6e27c5'</span>,
  <span class="hljs-attr">secondary</span>: <span class="hljs-string">'#ffb617'</span>,
  <span class="hljs-attr">danger</span>: <span class="hljs-string">'#f16623'</span>,
  <span class="hljs-attr">light</span>: <span class="hljs-string">'#f4f4f4'</span>,
  <span class="hljs-attr">dark</span>: <span class="hljs-string">'#222'</span>,
};
</code></pre>
<p>Now we need a way to switch between the two <code>theme</code> objects, let's use a select box for them, let's create a components folder and in there make a <code>ThemeSelect.js</code> component, we can worry about refactoring the <code>App.js</code> component when I'm not here :</p>
<h4 id="heading-themeselectjs">ThemeSelect.js</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> styled <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

<span class="hljs-keyword">const</span> Select = styled.select<span class="hljs-string">`
  margin: 2rem 0.5rem;
  padding: 0rem 0.5rem;
  font-family: Roboto;
  font-size: 1rem;
  border: 1px solid <span class="hljs-subst">${props =&gt; props.theme.light}</span>;
  box-shadow: 0px 0px 0px 1px rgba(0, 0, 0, 0.1);
  background: <span class="hljs-subst">${props =&gt; props.theme.light}</span>;
  border-radius: 2px;
`</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> SelectOpt = styled.option<span class="hljs-string">`
  font-family: Roboto;
  font-size: 1rem;
`</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThemeSelect</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">React</span>.<span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Select</span> <span class="hljs-attr">onChange</span>=<span class="hljs-string">{e</span> =&gt;</span> this.props.handleThemeChange(e)}&gt;
          <span class="hljs-tag">&lt;<span class="hljs-name">SelectOpt</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"theme1"</span>&gt;</span>Theme 1<span class="hljs-tag">&lt;/<span class="hljs-name">SelectOpt</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">SelectOpt</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"theme2"</span>&gt;</span>Theme 2<span class="hljs-tag">&lt;/<span class="hljs-name">SelectOpt</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">Select</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
    );
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> ThemeSelect;
</code></pre>
<p>You've probably noticed the <code>onChange={e =&gt; this.props.handleThemeChange(e)</code> event, we're going to add that method to the <code>App.js</code> component along with some state to manage what theme is selected.</p>
<h4 id="heading-appjs">App.js</h4>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> styled, { keyframes, ThemeProvider } <span class="hljs-keyword">from</span> <span class="hljs-string">'styled-components'</span>;

<span class="hljs-keyword">import</span> logo <span class="hljs-keyword">from</span> <span class="hljs-string">'./logo.svg'</span>;

<span class="hljs-keyword">import</span> { theme1, theme2 } <span class="hljs-keyword">from</span> <span class="hljs-string">'./theme/globalStyle'</span>;
<span class="hljs-keyword">import</span> ThemeSelect <span class="hljs-keyword">from</span> <span class="hljs-string">'./components/ThemeSelect'</span>;

<span class="hljs-comment">// our lovely styled-components here</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{
  state = {
    <span class="hljs-attr">theme</span>: theme1,
  };
  handleThemeChange = <span class="hljs-function"><span class="hljs-params">e</span> =&gt;</span> {
    <span class="hljs-keyword">let</span> theme = e.target.value;
    theme === <span class="hljs-string">'theme1'</span> ? (theme = theme1) : (theme = theme2);
    <span class="hljs-built_in">this</span>.setState({ theme });
  };
  render() {
    <span class="hljs-keyword">return</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThemeProvider</span> <span class="hljs-attr">theme</span>=<span class="hljs-string">{this.state.theme}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">AppWrapper</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">AppHeader</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">AppLogo</span> <span class="hljs-attr">src</span>=<span class="hljs-string">{logo}</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"logo"</span> /&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">AppTitle</span>&gt;</span>Welcome to React<span class="hljs-tag">&lt;/<span class="hljs-name">AppTitle</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">AppHeader</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">AppIntro</span>&gt;</span>
            Bootstrapped with <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>create-react-app<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span>.
          <span class="hljs-tag">&lt;/<span class="hljs-name">AppIntro</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">AppIntro</span>&gt;</span>
            Components styled with <span class="hljs-tag">&lt;<span class="hljs-name">code</span>&gt;</span>styled-components<span class="hljs-tag">&lt;/<span class="hljs-name">code</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">EmojiWrapper</span> <span class="hljs-attr">aria-label</span>=<span class="hljs-string">"nail polish"</span> /&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">AppIntro</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">ThemeSelect</span> <span class="hljs-attr">handleThemeChange</span>=<span class="hljs-string">{this.handleThemeChange}</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">AppWrapper</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">ThemeProvider</span>&gt;</span></span>
    );
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p>To summarise what we have done with <code>App.js</code> here is, add some state to default to theme1 where the two themes are imported as named exports of the <code>globalStyle.js</code> module.</p>
<p>Add a method to handle the change of the <code>ThemeSelect.js</code> component <code>handleThemeChange</code> this is where we can switch between the two <code>theme</code> objects.</p>
<p>Let's try it out, we should be able to switch between the two themes we've defined now.</p>
<h3 id="heading-extending-styled-components">Extending styled-components</h3>
<p>So far our app hasn't got many styled-components that are similar but what if we were to add some buttons…</p>
<pre><code class="lang-js"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> Button = styled.button<span class="hljs-string">`
  font-size: 1rem;
  border-radius: 5px;
  padding: 0.25rem 1rem;
  margin: 0 1rem;
  background: transparent;
  color: <span class="hljs-subst">${props =&gt; props.theme.primary}</span>;
  border: 2px solid <span class="hljs-subst">${props =&gt; props.theme.primary}</span>;
  <span class="hljs-subst">${props =&gt;
    props.primary &amp;&amp;
    css`<span class="css">
      <span class="hljs-selector-tag">background</span>: </span><span class="hljs-subst">${props =&gt; props.theme.primary}</span><span class="css">;
      <span class="hljs-selector-tag">color</span>: <span class="hljs-selector-tag">white</span>;
    `</span>}</span>;
`</span>;
</code></pre>
<p>Here I've added a <code>Button</code> component to the <code>globalStyle.js</code> for us to use in the <code>App.js</code> component. For the sake of convenience we're going to add it here, you may find if you have a lot of similar components that you are reusing throughout your app that it may be a good idea to add them all to a <code>components</code> folder.</p>
<p>We can import the <code>Button</code> as you would any other component and use it in the module, as we're extending it this means we only need to apply the specific styles we want for that button. But first in the <code>App.js</code> component we can specify a normal and a primary button:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Normal Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">primary</span>&gt;</span>Primary Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>Now to specify another button with the same css as the imported button we can extend it, like in this example we'll make the button take up 40% of the screen width and make the corners more rounded:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> BigButt = Button.extend<span class="hljs-string">`
  height: 3rem;
  font-size: 2rem;
  width: 40vw;
  border-radius: 30px;
`</span>;
</code></pre>
<p>Let's also apply the theme for an underline on <code>create-react-app</code> and <code>styled-components</code> by adding in an <code>Underline</code> styled-component:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Underline = styled.span<span class="hljs-string">`
  border-bottom: 4px solid <span class="hljs-subst">${props =&gt; props.theme.secondary}</span>;
`</span>;
</code></pre>
<p>Now we can switch the theme and have it applied to our components using the theme, pretty neat, right?</p>
<p>I have put all of the examples we have gone over here in a working example for you to play around with the theming and styled-components, enjoy.</p>
<p><a target="_blank" href="https://codesandbox.io/s/x26q7l9vyq?from-embed">https://codesandbox.io/s/x26q7l9vyq?from-embed</a></p>
<h3 id="heading-want-to-know-more">Want to know more?</h3>
<p>A great resource for getting started with styled-components which really helped me is <a target="_blank" href="https://twitter.com/simonswiss">Simon Vrachliotis</a>'s <a target="_blank" href="https://egghead.io/">egghead.io</a> styled-components <a target="_blank" href="https://egghead.io/playlists/styled-components-4169206d">playlist</a> which is a great foundation for starting out with styled-components ? the first lesson is for pro members but the rest are currently available to watch for free.</p>
<p>There's also the <a target="_blank" href="https://spectrum.chat/?t=54887141-57a9-4386-807c-ed950c4d5132">spectrum.chat</a> community and of course <a target="_blank" href="https://stackoverflow.com/questions/tagged/styled-components">Stack Overflow</a>.</p>
<h3 id="heading-thanks-for-reading">Thanks for reading</h3>
<p>If there is anything I have missed, or if you have a better way to do something then please let me know.</p>
<p>Find me on <a target="_blank" href="https://twitter.com/spences10">Twitter</a> or <a target="_blank" href="https://github.com/spences10/ama">Ask Me Anything</a> on GitHub.</p>
<blockquote>
<p><strong>You can read other articles like this on <a target="_blank" href="https://thelocalhost.blog/">my blog</a>.</strong></p>
</blockquote>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
