<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Siri Lööf on Medium]]></title>
        <description><![CDATA[Stories by Siri Lööf on Medium]]></description>
        <link>https://medium.com/@siriloof?source=rss-839ab57f2375------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K2P6KZledaWWtzan8m1V2g.jpeg</url>
            <title>Stories by Siri Lööf on Medium</title>
            <link>https://medium.com/@siriloof?source=rss-839ab57f2375------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:55:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@siriloof/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Test Driven Development (TDD) with React Testing Library & Mock Service Worker]]></title>
            <link>https://itnext.io/test-driven-development-tdd-with-react-testing-library-mock-service-worker-b23c9fedf6fa?source=rss-839ab57f2375------2</link>
            <guid isPermaLink="false">https://medium.com/p/b23c9fedf6fa</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Siri Lööf]]></dc:creator>
            <pubDate>Fri, 07 Aug 2020 13:04:07 GMT</pubDate>
            <atom:updated>2020-08-07T13:54:27.637Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tvf7rMSGPQA7XnA38Gv9Iw.png" /><figcaption>Logos: React, Testing Library &amp; Mock Service Worker</figcaption></figure><p><em>Let’s step up our testing game with two useful libraries that lend themselves excellently to a TDD approach.</em></p><h3>Setting up</h3><p>Whenever I want to try out something React-related, I use the library <a href="https://create-react-app.dev/docs/getting-started/">create-react-app</a>. It gives you a ready-to-work-with basic React application with no configuration needed. Recent versions also come bundled with React Testing Library, so if you use the latest <em>create-react-app</em>, you can start using React Testing Library straight away. If not — install <a href="https://www.npmjs.com/package/@testing-library/react">@testing-library/react</a> and <a href="https://www.npmjs.com/package/@testing-library/jest-dom">@testing-library/jest-dom</a> in your existing React application.</p><p>I am going to implement the following functionality: a simple recipe list with a search function. It will look something like this to a user in a mobile browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQ5oG2QrMA00Pa7K7RWyUw.png" /><figcaption>Image credits: Burger Photo by <a href="https://unsplash.com/@robinstickel?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Robin Stickel</a> on <a href="https://unsplash.com/s/photos/burger?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>, French Toast Photo by <a href="https://unsplash.com/@miracletwentyone?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Joseph Gonzalez</a> on <a href="https://unsplash.com/s/photos/food?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>, Salmon Photo by <a href="https://unsplash.com/@simplethemes?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Casey Lee</a> on <a href="https://unsplash.com/s/photos/food?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Starting with a failing test</h3><p>I want to use a TDD approach, so let’s start with a failing test. At this point, there is no component yet, so of course whatever test we write is going to fail. But let’s start small; I want a component named ‘Recipes’ that renders the expected heading text. Here is my test for that expectation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb9598e9585770cfdb66e6ff7d1d38ae/href">https://medium.com/media/eb9598e9585770cfdb66e6ff7d1d38ae/href</a></iframe><p>React testing library exports a <em>render</em> method, which will render a component and all of its child components. It also exports a <em>screen</em> object, holding a number of <a href="https://testing-library.com/docs/dom-testing-library/api-queries">queries</a> we can use to select different elements in our rendered component (and its child components too). The <strong>getByRole </strong>query lets me select the heading element and make an assertion on its text content.</p><p>Why select the heading element by its role and not for example a CSS class? The guiding principle of React Testing Library is <a href="https://testing-library.com/">“The more your tests resemble the way your software is used, the more confidence they can give you.”</a> Therefore, we want to write our tests as close as possible to how the ultimate tester — the end user — will be using the application. Users don’t see CSS classes or data attributes; they interact with text, label text and semantic elements and roles. Using queries such as <strong>getByRole</strong> also encourages us to write accessible code, since these selectors are available to everyone, including users of screen readers.</p><h3>Making the test pass</h3><p>Our first test fails as expected.<strong> Recipes is not defined.</strong> But this is the first step in TDD — a failing test. Now, let’s make it pass by writing the simplest possible &lt;Recipes /&gt; component with the correct heading and then importing it in our test file. Now, let’s re-run the test. It passes!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09ed40895c0385bf3a39039f58fdee08/href">https://medium.com/media/09ed40895c0385bf3a39039f58fdee08/href</a></iframe><p>Using further queries, we can make similar expectations for the input element and the “Find” button. The button also has a role, but for the input field, I will use the <strong>getByPlaceholderText</strong> query, since that is probably the closest query to how the user would find it on the page.</p><p>Start with a failing test…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e60098814627c0e944d5449a056733f/href">https://medium.com/media/9e60098814627c0e944d5449a056733f/href</a></iframe><p>… and implement the changes necessary to make it pass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c732c7e9c8d46e8a65fb1c3afc0d2b7/href">https://medium.com/media/0c732c7e9c8d46e8a65fb1c3afc0d2b7/href</a></iframe><p>This way, we know what we expect from our code and more importantly — we will know if we break any functionality if the previously passing tests suddenly fail.</p><p>An important step in TDD is the <em>refactor</em> step, where we improve our code to for example make it easier to read, become more efficient and remove any duplication. The test should still pass after we refactor.</p><h3><strong>Setting up our mocks</strong></h3><p>When the application first renders, I want to display a list of all my recipes, just like in the visual design above. This requires some kind of communication with an API. We are going to use <a href="https://mswjs.io/">Mock Service Worker</a> to mock the HTTP-requests, so that we can control the response data. Install Mock Service Worker with npm like this:</p><pre>npm install msw --save-dev</pre><p>With Mock Service Worker, we are not mocking a specific module (unlike if we were to use Jest.mock), which means that it makes no difference if I use <em>fetch</em> or a third-party library such as <em>axios</em> to get the data. This makes it incredibly flexible. Let’s add the following imports to our test file:</p><pre>import { <strong><em>rest </em></strong>} from &#39;msw&#39;;<br>import { <strong><em>setupServer </em></strong>} from &#39;msw/node&#39;;</pre><p>Here is how I set up mocking a call to the recipe list endpoint:</p><pre>GET /api/recipes</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c52670c19778fd1777c5b1fd0a9ec08c/href">https://medium.com/media/c52670c19778fd1777c5b1fd0a9ec08c/href</a></iframe><p>If you have worked with NodeJS and Express, the syntax looks very familiar. GET requests to ‘/api/recipes’ will respond with JSON containing the allRecipes array, just like a real API would. These two lines make sure the server starts listening (intercepting) before the tests run and closes its connection when the tests in this file have finished running:</p><pre>beforeAll(() =&gt; server.listen());<br>afterAll(() =&gt; server.close());</pre><h3><strong>Testing asynchronous code</strong></h3><p>Let’s write a new test that verifies that the list of recipes is displayed when the component renders. Since the displayed recipes are the result of an asynchronous operation, we need to make sure the test waits a while before asserting on their appearance. React Testing Library has asynchronous queries for this purpose — the <strong>findBy*</strong> queries. Should the queried element not exist after a certain number of retries, the test will time-out and fail. Using <em>async await </em>in our test, we can find all elements with a <em>listitem </em>role (&lt;li&gt; elements), once they have been fetched and rendered:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5ba2e1d5ec8d74a0d12102a1679eb61/href">https://medium.com/media/b5ba2e1d5ec8d74a0d12102a1679eb61/href</a></iframe><p>We can now write some code in our &lt;Recipes /&gt; component, to make this test pass too. It could look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f898ab5feae9210513c2400eeff51837/href">https://medium.com/media/f898ab5feae9210513c2400eeff51837/href</a></iframe><h3><strong>Simulating user interaction</strong></h3><p>React Testing Library exposes another method for this purpose — <strong>fireEvent</strong>. Again, let’s start by writing a test scenario we know will fail:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d27e99af08bb0827b5e8d002fced52c/href">https://medium.com/media/0d27e99af08bb0827b5e8d002fced52c/href</a></iframe><p>FireEvent is imported from the same place as <strong>render</strong> and <strong>screen</strong>:</p><pre>import { <strong><em>fireEvent</em></strong>, <strong>render</strong>, <strong><em>screen </em></strong>} from &#39;@testing-library/react&#39;;</pre><p>With <strong>fireEvent</strong>, we can simulate both a <em>change</em> event and a <em>click</em> event, to make the test behave closely to how a user would type and submit the form. If the user types in the word “fish” in the input field and clicks the “Find” button, we expect to see the message “showing results for fish:” and only one&lt;li&gt; element, its text content being “Salmon”.</p><p>But wait — our mock has been set up to always return the full list of recipes when we make a GET call to the ‘api/recipes’ endpoint. We have to be able to handle request query strings to mock a filtered response. Luckily, this is easily done with Mock Service Worker.</p><h3>Mocking calls with query strings</h3><p>In our GET request handler, we can access the query strings of the request with <strong>req.url.searchParams.</strong> By making a small change to the request handler, we can ensure that when the test encounters a requests to:</p><pre>GET /api/recipes?ingredient=fish</pre><p>our mock will return filtered data; an array containing just the salmon recipe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c099ee1f5028503e89b64d6c7431ca1a/href">https://medium.com/media/c099ee1f5028503e89b64d6c7431ca1a/href</a></iframe><p>Now we can go ahead and implement the necessary logic in &lt;Recipes /&gt; to make this test pass! At the end of this article, I have added the full implementation, but here is a snippet showing the fetch call:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60ab12ff28c5ee145f9dbd70e37f436b/href">https://medium.com/media/60ab12ff28c5ee145f9dbd70e37f436b/href</a></iframe><h3>Mocking server-side errors</h3><p>We may want to implement some error handling into our recipe application as well. Let’s start with a failing test, as usual, outlining our expectations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a13faa35883b5992591a74604e00c52/href">https://medium.com/media/0a13faa35883b5992591a74604e00c52/href</a></iframe><p>In order to make our mock return Internal Server Error, we simply create a response handler with a status of 500 and an “Internal Server Error” message, similar to how a real API would respond. But, we only want the mock to respond differently in this particular test case — the previously written tests should still expect a successful mock API response. Mock Service Worker lets us override the previous response handler with <em>server.use </em>inside a particular test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaaf32eaf1e81a4d19b8a26d9a494f51/href">https://medium.com/media/aaaf32eaf1e81a4d19b8a26d9a494f51/href</a></iframe><p>It is important that when we start overriding previously mocked responses in a test suite, we add the following line above our tests:</p><pre>afterEach(() =&gt; server.resetHandlers());</pre><p>This ensure any handlers set during runtime of the test, will not “leak” into subsequent tests.</p><h3>Wrapping up</h3><p>There are of course many more features, error handling and form validation we could implement with a test-driven approach, but hopefully now you have some inspiration to get started in your own project!</p><p>I want to stress that it is not important <em>how</em> you implement the code you are testing with React Testing Library and Mock Service Worker. I am using a function component with the <strong>useState</strong> and <strong>useEffect</strong> hooks in my example, and <strong>fetch</strong> to retrieve the data. However, I can refactor this component into a class component and even smaller child components and the tests would still pass, as long as the logic doesn’t break. Just like your end user doesn’t care how many child components are rendered or if you handle state with <strong>setState</strong> or <strong>useState</strong>, neither does React Testing Library. That is a huge advantage compared to other testing tools. Knowing that we don’t have to worry about breaking tests whenever we make changes to implementation details is a nice feeling. It also goes very well with the TDD philosophy, since an important step in the TDD process is <em>refactoring</em>.</p><p>Here is a full example, driven by our test cases above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c73fe02580fa4dfda75b495688a7c496/href">https://medium.com/media/c73fe02580fa4dfda75b495688a7c496/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b23c9fedf6fa" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/test-driven-development-tdd-with-react-testing-library-mock-service-worker-b23c9fedf6fa">Test Driven Development (TDD) with React Testing Library &amp; Mock Service Worker</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Responsive Background Images Using React Hooks]]></title>
            <link>https://itnext.io/responsive-background-images-using-react-hooks-941af365ea1f?source=rss-839ab57f2375------2</link>
            <guid isPermaLink="false">https://medium.com/p/941af365ea1f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Siri Lööf]]></dc:creator>
            <pubDate>Fri, 22 Feb 2019 12:31:50 GMT</pubDate>
            <atom:updated>2020-04-16T15:35:55.950Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Getting to know the new React Effect- and State Hooks in a real-life example.</em></p><p>Working with full-screen background images can be difficult. I often find that very few full-screen images look good in both landscape and portrait orientation, so I like to use different images depending on the viewport width. Usually I would let media queries in CSS handle the responsiveness of the site, but sometimes image URLs are only available in JavaScript, for example if loaded in via an Ajax request.</p><p>Faced with these issues in a React application, I decided to try out the new <a href="https://reactjs.org/docs/hooks-overview.html">Hooks API</a> to solve them. With React Hooks, we can both subscribe to changes in viewport size and set the appropriate background image based on the width of the screen! 🎉</p><p>In my React app, I’ve chosen one background image adapted for desktop screens and another suitable for mobile, as per this design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*JzPim0t5MLzqNlFIDkXCQQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZIzlTaD6PGhzITgdSpp7g.png" /><figcaption>Narrow screens use an image adapted for portrait orientation and wider screens use the landscape image</figcaption></figure><p>Below is my React component. Note that this is a f<em>unctional component, </em>since Hooks do not work with class components. Screens narrower than 650px will use the image adapted for mobile. Wider screens will use the desktop image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46670c19352498d998d7e136b4e60f5a/href">https://medium.com/media/46670c19352498d998d7e136b4e60f5a/href</a></iframe><p>I also have some basic CSS to get the background image to be full-screen and to position the text:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/424ae44a621915c16fa8de28761b7c85/href">https://medium.com/media/424ae44a621915c16fa8de28761b7c85/href</a></iframe><p>Now this works fine even without Hooks when the component first renders, but if I start re-sizing the window, even below the 650px breakpoint, the image url doesn’t change. To get this desired side effect, we need to attach a listener to the window’s re-size event, by using the <a href="https://reactjs.org/docs/hooks-effect.html">Effect Hook</a>.</p><h3>The Effect Hook</h3><p>The Effect Hook, useEffect, lets us perform side effects in a React functional component. With this hook, I only have to add the event listener once and it runs every time the component renders. It’s basically the equivalent of a class component’s componentDidMount and componentDidUpdate lifecycle methods combined. Here’s what the effect looks like inside my App component:</p><pre>useEffect(() =&gt; {        <br>  window.addEventListener(&#39;resize&#39;, handleWindowResize);         <br>});</pre><p>I also want to remove the event listener when the component unmounts. In a class component, this would be done in the componentWillUnmount method. With the Effect Hook, we can keep all the code related to the side effect in one place — since the return value of useEffect acts as a cleanup method. Here’s what that looks like:</p><pre>useEffect(() =&gt; {        <br>  window.addEventListener(&#39;resize&#39;, handleWindowResize);</pre><pre>  return () =&gt; {            <br>    window.removeEventListener(&#39;resize&#39;, handleWindowResize);  <br>  }  <br>});</pre><p>By default, the Effect Hook runs every time the component mounts and again every time it updates. But this is unnecessary in my case. To fix this, we will use the second argument to useEffect, which is an array of dependencies. Since I have no dependencies to my hook, I pass an empty array as the second argument, and this makes the side effect run only when the component mounts and unmounts, which is what we want:</p><pre>useEffect(() =&gt; {        <br>  window.addEventListener(&#39;resize&#39;, handleWindowResize);</pre><pre>  return () =&gt; {            <br>    window.removeEventListener(&#39;resize&#39;, handleWindowResize);      <br>  }  <br>}, []); //empty array makes side effect only run on mount and unmount</pre><h3>The State Hook</h3><p>In my handleWindowResize function, I now want to update the component’s state with the new value of window.innerWidth. But hang on, this is a functional component, so how can I change its state without refactoring to a class component? The answer is: with the <a href="https://reactjs.org/docs/hooks-state.html">State Hook.</a></p><p>The State Hook lets us use component state even in functional components. The way to declare a state variable with useState looks like this:</p><pre>const [windowWidth, setWindowWidth ] = useState(window.innerWidth);</pre><p>The first item in the array, windowWidth, is the equivalent to this.state.windowWidth in a class component. The second item, setWindowWidth, is a setter function, equivalent to setState({ windowWidth: window.innerWidth }) in a class component. The only argument to useState is the initial value of that particular state variable, in my case the initial width of the window.</p><p>Finally, this is what the handleWindowResize function looks like, and I declare it inside my useEffect hook. It calls the setter function for updating the windowWidth state:</p><pre>useEffect(() =&gt; {<br>  const handleWindowResize = () =&gt; {<br>    setWindowWidth(window.innerWidth);<br>  }</pre><pre>  window.addEventListener(&#39;resize&#39;, handleWindowResize);</pre><pre>  return () =&gt; {            <br>    window.removeEventListener(&#39;resize&#39;, handleWindowResize);      <br>  }  <br>}, []);</pre><p><strong><em>Edit</em></strong><em>: In the code section above, it looks like setWindowWidth is a dependency to the useEffect hook, since it’s declared outside the hook. While it is true that it is technically a dependency and we could specify it in our dependency array, we don’t actually have to because values from useState is </em><a href="https://overreacted.io/a-complete-guide-to-useeffect/"><em>guaranteed to be static by React.</em></a></p><p>My React component now looks like this with both the State Hook and the Effect Hook in use:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b1024b4e5438927091c35977b75b5d5/href">https://medium.com/media/2b1024b4e5438927091c35977b75b5d5/href</a></iframe><p>Now the state variable windowWidth is updated every time the window is re-sized! 🎉</p><h3>Custom Hooks</h3><p>There might be other components in the application that need to know about the window width too. To avoid having to write the same code in multiple components, we can extract the code handling the side effect and the stateful logic and create a <a href="https://reactjs.org/docs/hooks-custom.html">custom hook</a>. A custom hook is just a JavaScript function that calls other React Hooks. The name of the function should start with ‘use’, according to the React documentation. I decided to call my custom hook useWindowWidth and here it is in action:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10658314316a066de8689f3a8aa190c2/href">https://medium.com/media/10658314316a066de8689f3a8aa190c2/href</a></iframe><h3>Verdict</h3><p>When I first saw the documentation for React Hooks I wasn’t sure how useful they would be in my daily work, but now that I’ve started introducing them in projects, especially the Effect Hook has become very appealing. I like that all code related to one side effect is kept in the same place and not scattered throughout various lifecycle methods. There’s a lot less code to write than creating a class component with the same logic. The syntax is still a bit weird to me, but I guess it’s just a matter of preference and habit.</p><p>Hopefully, as hooks become more frequently used I will discover further benefits and use cases. If not, at least it’s good to know that we now have the choice to use functional- or class components when handling state and side effects in React.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=941af365ea1f" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/responsive-background-images-using-react-hooks-941af365ea1f">Responsive Background Images Using React Hooks🍍</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Theming Simplified with CSS Variables]]></title>
            <link>https://medium.com/@siriloof/dynamic-theming-simplified-with-css-variables-338f1c15050a?source=rss-839ab57f2375------2</link>
            <guid isPermaLink="false">https://medium.com/p/338f1c15050a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[custom-properties]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[theming]]></category>
            <category><![CDATA[css-custom-properties]]></category>
            <dc:creator><![CDATA[Siri Lööf]]></dc:creator>
            <pubDate>Wed, 23 Jan 2019 15:17:03 GMT</pubDate>
            <atom:updated>2019-01-24T08:53:31.623Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1J2MWl_SJ6ECZrciaytfyg.jpeg" /></figure><p>Did you know that pure CSS now supports variables — also known as <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/--*">custom properties</a>?</p><p>Up until recently we have had to rely on preprocessors such as Sass or LESS to be able to use variables in our stylesheets. Custom properties, however, enable us store and reuse values in CSS, natively, without installing any dependencies! And because they behave like regular CSS properties (hence the name), we can also use custom properties as a nice and lightweight theming tool. Here’s how:</p><h3>The Challenge: Update Web Application Style in Runtime</h3><p>Say we are working on a single-page web application where the user may want to toggle between a “dark theme” and a “light theme”, and subsequently the visual style of the application will update without re-loading the page. Ideally, we would like the HTML and JavaScript to remain largely the same in both themes; we simply want to update the values of some colors, fonts and other visual style whenever the user clicks a “toggle theme” button.</p><h3>The Solution: CSS Custom Properties</h3><p>Before custom properties, the way to support variables in CSS was to use a preprocessor like Sass or LESS. Preprocessors can be extremely useful, but since their code is eventually compiled into pure CSS, their variables are static. This makes it difficult to create the theming we want without loading in separate stylesheets for each theme and/or writing lots of additional JavaScript and inline style. Custom properties on the other hand, come with some cool bonus features, such as:</p><ul><li>Their values can be updated dynamically.</li><li>They can be accessed and changed with JavaScript.</li><li>They are aware of the DOM’s structure, inheritance and cascade.</li><li>They can be viewed in browser developer tools.</li><li>They can be used alongside existing CSS preprocessors.</li></ul><h3>How To Use Custom Properties</h3><p>If you are familiar with using CSS preprocessors, you may have seen variables declared similarly to below. A variable can be assigned the value of for example a string, a unit or a color hex code, to name a few usages. In LESS, we declare and use variables like in this example:</p><pre>@primary-color: #aaccee;</pre><pre>.button {<br>   color: @primary-color;<br>}</pre><p>Custom properties have a slightly different syntax. We declare a variable using the -- notation and access it by using the var() function, like this:</p><pre>:root {<br>  --primary-color: #aaccee;<br>}</pre><pre>.button {<br>   color: var(--primary-color);<br>}</pre><h4>Custom properties are aware of specificity and scope</h4><p>Don’t worry if you haven’t seen the :root selector before. Custom properties must be declared inside a selector block. The :root selector is like selecting the html tag but with a higher specificity. A custom property declared in the :root scope therefore targets the entire site, unless overwritten inside a selector with higher specificity, just like any other CSS property.</p><p>In the below example, the variable --background-color will have the value white except when used inside an element with the .dark class.</p><pre>:root {<br>  --background-color: white;<br>}</pre><pre>.dark {<br>  --background-color: black;<br>}</pre><h3>The Result: Pure CSS Magic</h3><p>The below pen is a simple example of theming with CSS custom properties. I’m using pure JavaScript to toggle a .dark-theme class on the body, but of course this can be done in your favourite JavaScript framework too.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fsiriloof%2Fembed%2Fpreview%2FWLaKeN%3Fheight%3D600%26slug-hash%3DWLaKeN%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;url=https%3A%2F%2Fcodepen.io%2Fsiriloof%2Fpen%2FWLaKeN&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/bda9bd3ebdf4086a2133d451a8ef8b16/href">https://medium.com/media/bda9bd3ebdf4086a2133d451a8ef8b16/href</a></iframe><p>Because custom properties cascade just like all native CSS, the .dark-theme selector is more specific than the :root selector and therefore the values are overwritten with the more specific ones, when the .dark-theme class is applied to the body of the document. Variables can hold urls too, so we can even update the CSS background-images this way.</p><p>Now we can easily scale this up to handle a third or even a fourth theme! With minimal changes in JavaScript and CSS, we can change the style of a component or the entire UI. Very powerful!</p><h3>Browser Support</h3><p>Custom properties <a href="https://caniuse.com/#search=custom%20properties">are supported by most browsers</a>, including Edge, but sadly not Internet Explorer. However, if we are OK with users of IE not getting the full multi-theme experience, we can combine custom properties with static fallbacks (or preprocessor variables) to serve IE-users a simpler, single-theme version of the page.</p><p>In the example below, browsers that support the custom properties syntax will use the value of --primary-color . The browsers that do not support the syntax will simply ignore it and use the previously declared static value instead. For this reason, it’s important to remember to declare the fallback <em>before</em> the custom property.</p><pre>.button {<br>   background-color: blue; //static fallback for IE<br>   background-color: var(--primary-color);<br>}</pre><p>The fallback value won’t dynamically update of course, but using static values together with custom properties can be used to adopt a progressive enhancement strategy.</p><h3>Conclusion</h3><p>CSS custom properties are powerful, easy to use and relatively cross-browser compatible. Not only do we get the benefits of reusing and storing values in the same way we benefit from CSS preprocessor variables; custom properties are also able to update their value dynamically <em>after</em> the page has loaded.</p><p>This makes custom properties a handy and lightweight theming tool for our web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=338f1c15050a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>