KAT CODES

journey through web development

Page 2 of 6

Create a simple toggle switch in React

Dark themes have become really popular in the recent years, and a lot of websites have given their users the ability to choose between light and dark mode. This personalisation also increases accessibility, as some people struggle to read black letters on white background, and prefer to switch to light letters on a dark background.
Toggle switch is, in my opinion, the best way to incorporate light/dark mode feature. Today I’m gonna show you how to create a simple, yet effective toggle switch.

The first thing we need is a design of your toggle.
I’ve made mine using Figma. The sun and moon icons are from Iconify plugin, and gradients were made with uiGradients plugin. When you’re happy with your design, save your file and export the icons (if your have them of course, as they are not mandatory).

Now open the editor of your choice, I’m using Visual Studio Code on my personal computer. Open the folder in which you would like your project directory be. Then, open the terminal and type:

npx create-react-app toggle 
# toggle is the name of your project

when your react app is created, go to your project’s directory using:

cd toggle 
#again, toggle is the name of your project

the last step before we can start our application is starting the server:

npm start

Your project should now open up in your browser, and you should see generic React app page.

We will be using styled-components, so we need to install it in our project. Open a new terminal window and type:

npm install-s styled-components

Ok, so let’s have a look at our project’s folders. We have node_modules, public, src, .gitignore, package-lock.json, package.json and README.md. In the src folder, if your have any icons, create a folder for your assets and them here. Create a folder callled components, in which add a new file: toggle.js

Now, open App.js file and delete everything from inside the div className=”App”. This was what you saw in the generic React page in your browser. We won’t be needing in. Ok, now we need to import our component. At the top of the file, type:

import ToggleComponent from './components/toggle';

Now we can add this component inside the div, and this is how our App.js file should look like now:

import './App.css';
import ToggleComponent from './components/toggle';
function App() {
  return (
    <div className="App">
        <ToggleComponent />
    </div>
  );
}
export default App;

Save and then open toggle.js file. At the top of the document, import React, useState, useEffect and also styled (our styled-components) and keyframes for animations.

import React, { useState , useEffect} from "react";
import styled, { keyframes } from 'styled-components';

To help us out later on, let’s create few const’s that will keep some of our values:

const time = '0.1s';
const lightBackground = 'linear-gradient(90deg, #EAC29C 0%, #EDE8CF 100%)';
const darkBackground = 'linear-gradient(90deg, #46517F 0%, #8DA5B4 100%)';
const setAnimation = (from, to) => keyframes({from: from, to: to});

Components can have one default function, and many regular ones. Let’s create our default one, which will be exported so we can use it in App.js

function ToggleComponent() {
 
    return (
        <OuterWrapper>
            <StyledWrapper>
                <Header>
                    Toggle Switch
                </Header>
                <Toggle />
            </StyledWrapper>
        </OuterWrapper>
      
)}
export default ToggleComponent;

Inside the return braces we will code our component, just like you would code in HTML, but with a twist of styled components.
Styled components let you write CSS inside the .js file, so you don’t have to go back and forth between files and those styled will only apply for that specific component.

To create a styled component, above the function type:

const OuterWrapper = styled.div`
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: ${lightBackground};
    animation: ${time} ${({ showBackground }) => showBackground && setAnimation({ background: 
    lightBackground }, { background: darkBackground })} linear;
    animation-fill-mode: forwards;
`;

this is my styled div named OuterWrapper. You can see, inside is just a regular CSS values. Ok let’s create const’s for all divs, h1 and span. All the changes will be showing in your browser straight away, so don’t be afraid to use Inspect tab and play around with different values!

const OuterWrapper = styled.div`
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: ${lightBackground};
    animation: ${time} ${({ showBackground }) => showBackground && setAnimation({ background: 
    lightBackground }, { background: darkBackground })} linear;
    animation-fill-mode: forwards;
`;
const StyledWrapper = styled.div`
    display: flex;
    justify-content: center;
    flex-direction: column;
    height: 50vh;
    margin:0 auto;
    z-index: 10000;
`;
const Header = styled.h1`
    color: #333333;
    animation: ${time} ${({ showLightfont }) => showLightfont && setAnimation({ color: 
    '#333333' }, { color: '#ffffff' })} linear;
    animation-fill-mode: forwards;
    position: relative;
    font-size: 40px;
    font-family: 'Raleway Dots', cursive;
    display: flex;
    align-items: center;
    margin-bottom:40px;
`;
const StyledToggle = styled.div`
   border-radius: 50px;
   background:  linear-gradient(90deg, #FFA751 0%, #FFE259 100%);
   animation: ${time}  ${({dark}) => dark && setAnimation({background: lightBackground}, 
   {background: darkBackground})} linear;
   animation-fill-mode: forwards;
   height: 32px;
   width: 58px;
   display:flex;
   position: relative;
   align-self: center;
   z-index:100;
   box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.04), 0px 0px 2px rgba(0, 0, 0, 0.06), 0px 0px 1px 
   rgba(0, 0, 0, 0.04);
`;
const StyledSwitch = styled.span`
   background: #ffffff url('./assets/smiley-sun.svg') no-repeat center;
   z-index: 101;
   width:28px;
   height: 26px;
   border-radius: 50px;
   display:flex;
   justify-content:center;
   align-self: center;
   margin-left: 3px;
   margin-top:0.5px;
   z-index: 10000;
   animation: ${time}  ${({dark}) => dark && setAnimation({marginLeft: '3px', background: 
   '#ffffff url(\'./assets/smiley-sun.svg\') no-repeat center'}, {marginLeft: '26px', 
   background: '#ffffff url(\'./assets/smiley-moon.svg\') no-repeat center'})} linear;
   cursor: pointer;
   animation-fi

Ok let’s create a Toggle component function! Having it separate from the default function, we will be able to use our toggle anywhere else in the app, and have multiple different toggles. DRY coding! (don’t repeat yourself)

const Toggle = (props) => {
    const [dark, setDark] = useState(false);
    const {onDark, onNotDark} = props;
    useEffect(() => {
        if (!dark) {
            onNotDark();
            return;
        }
        onDark();
    }, [dark])
    const handleClick = () => {
        setDark(!dark)
    }; 
    return (
        <StyledToggle dark={dark}>
            <StyledSwitch dark={dark} onClick={handleClick} />
        </StyledToggle>
    )};

In our toggle, we are using states for light and dark setting. We have also added an onClick event to the StyledSwitch span.

We need to remember that any change of state can only go down from a parent to the child element. A child component cannot be responsible for those (because kids aren’t responsible, right? 😂) To make our toggle work, we need to give a parent (our default ToggleComponent) some responsibility.

function ToggleComponent() {
    const [showBackground, setShowBackground] = useState(false);
    const [showLightfont, setShowLightfont] = useState(false);
    const handleNotDark = () => setShowBackground(false) & setShowLightfont(false);
    const handleDark = () => setShowBackground(true) & setShowLightfont(true);
    
    return (
        <OuterWrapper showBackground={showBackground}>
            <StyledWrapper>
                <Header showLightfont= {showLightfont}>
                    Toggle Switch
                </Header>
                        <Toggle onNotDark= {handleNotDark} onDark= {handleDark} />
            </StyledWrapper>
        </OuterWrapper>
);
}

This is how our parent looks like now.

import React, { useState , useEffect} from "react";
import styled, { keyframes } from 'styled-components';
const time = '0.1s';
const lightBackground = 'linear-gradient(90deg, #EAC29C 0%, #EDE8CF 100%)';
const darkBackground = 'linear-gradient(90deg, #46517F 0%, #8DA5B4 100%)';
const setAnimation = (from, to) => keyframes({from: from, to: to});
const OuterWrapper = styled.div`
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    background: ${lightBackground};
    animation: ${time} ${({ showBackground }) => showBackground && setAnimation({ background: 
    lightBackground }, { background: darkBackground })} linear;
    animation-fill-mode: forwards;
`;
const StyledWrapper = styled.div`
    display: flex;
    justify-content: center;
    flex-direction: column;
    height: 50vh;
    margin:0 auto;
    z-index: 10000;
`;
const Header = styled.h1`
    color: #333333;
    animation: ${time} ${({ showLightfont }) => showLightfont && setAnimation({ color: 
    '#333333' }, { color: '#ffffff' })} linear;
    animation-fill-mode: forwards;
    position: relative;
    font-size: 40px;
    font-family: 'Raleway Dots', cursive;
    display: flex;
    align-items: center;
    margin-bottom:40px;
`;
const StyledToggle = styled.div`
   border-radius: 50px;
   background:  linear-gradient(90deg, #FFA751 0%, #FFE259 100%);
   animation: ${time}  ${({dark}) => dark && setAnimation({background: lightBackground}, 
   {background: darkBackground})} linear;
   animation-fill-mode: forwards;
   height: 32px;
   width: 58px;
   display:flex;
   position: relative;
   align-self: center;
   z-index:100;
   box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.04), 0px 0px 2px rgba(0, 0, 0, 0.06), 0px 0px 1px 
   rgba(0, 0, 0, 0.04);
`;
const StyledSwitch = styled.span`
   background: #ffffff url('./assets/smiley-sun.svg') no-repeat center;
   z-index: 101;
   width:28px;
   height: 26px;
   border-radius: 50px;
   display:flex;
   justify-content:center;
   align-self: center;
   margin-left: 3px;
   margin-top:0.5px;
   z-index: 10000;
   animation: ${time}  ${({dark}) => dark && setAnimation({marginLeft: '3px', background: 
   '#ffffff url(\'./assets/smiley-sun.svg\') no-repeat center'}, {marginLeft: '26px', 
   background: '#ffffff url(\'./assets/smiley-moon.svg\') no-repeat center'})} linear;
   cursor: pointer;
   animation-fill-mode: forwards;
`;
const Toggle = (props) => {
    const [dark, setDark] = useState(false);
    const {onDark, onNotDark} = props;
    useEffect(() => {
        if (!dark) {
            onNotDark();
            return;
        }
        onDark();
    }, [dark])
    const handleClick = () => {
        setDark(!dark)
    }; 
    return (<StyledToggle dark={dark}>
        <StyledSwitch dark={dark} onClick={handleClick}></StyledSwitch>
    </StyledToggle>
    )};
function ToggleComponent() {
    const [showBackground, setShowBackground] = useState(false);
    const [showLightfont, setShowLightfont] = useState(false);
    const handleNotDark = () => setShowBackground(false) & setShowLightfont(false);
    const handleDark = () => setShowBackground(true) & setShowLightfont(true);
    
    return (
        <OuterWrapper showBackground={showBackground}>
            <StyledWrapper>
                <Header showLightfont= {showLightfont}>
                    Toggle Switch
                </Header>
                        <Toggle onNotDark= {handleNotDark} onDark= {handleDark} />
            </StyledWrapper>
        </OuterWrapper>
);
}
export default ToggleComponent;

And that is our complete component file. If your would like a nice fonts, either import the font into your project, or add a link into the head of index.html file.

OK time to deploy your project and publish it! Github pages will be the best option for our needs today.
Commit your work, then go into your github account and create a new empty repository. Follow the steps to add existing repository:

git remote add origin https://github.com/your-username/name-of-your-project.git
git branch -M main
git push -u origin main

Now we need to install gh-pages package. In your terminal, type:

npm install gh-pages --save-dev

In package.json file, add:

"homepage" : "http://katwlodarczyk.github.io/toggle-switch-react" 
#add this after name of the project. this is your github pages url

and lastly, we need to add some new scripts:

"predeploy": "npm run build",
"deploy": "gh-pages -d build"

Ok. let’s deploy! In the terminal, type:

npm run deploy

Wait and…. viola!

You can see my finished project here:

https://katwlodarczyk.github.io/toggle-switch-react/

GitHub repository to see the whole code:

https://github.com/katwlodarczyk/toggle-switch-react

Toggle switch project on Behance:

https://www.behance.net/gallery/108743485/Toggle-switch


If you’ve done your very own awesome toggle, share the link with me!

Liked this post? Share:

Huge list of Figma plugins you should know about

Do you use Figma? If you do, then this list is just for you! Big list of my favourite figma plugins. They will make your work easier, faster and much more enjoyable!

Brandfetch

Type in any brand and in seconds you have access to its logo, brand colours, brand fonts and Image. Saves you a lot of time googling that stuff manually! They even had katvonwiesendorf.com (my photography blog) on, so I’m impressed!

My rating:

Rating: 4 out of 5.

Blobs

This is a plugin you didn’t know you needed in your life until you use it for the first time! I absolutely love Blobs, few clicks and you have a lovely shaped blob to use in your design. Adds a nice depth and a lot of coolness to your work!


My rating:

Rating: 5 out of 5.

Material Design Icons

Enormous collection of icons to use in your designs. Export as and svg and job done! Simple and easy. 9/10 times you will find the icon you need there.

My rating:

Rating: 4.5 out of 5.

Humaaans for Figma

My love for illustrations and illustrated people began from this plugin. Choose ready made person or create you own using components, change colours and there you have a little person! There are certain limitations (hairstyles for example) but it’s still really cool plugin worth installing.
For observant readers, yes, the illustration on my banner is made using this plugin!


My rating:

Rating: 5 out of 5.

Metaball

The newest find of mine, definitely useful, just didn’t really had an idea where I could actually use it! 😂 This plugin creates 2D metaball objects from circles, so when you need a meta shape, it will be a godsend for you.


My rating:

Rating: 3 out of 5.

Logo creator

Nice little plugin for those times when you quickly need some dummy logo. They are still in beta, so options are limited, but I still found it useful to have. Hopefully their collection will grow overtime.


My rating:

Rating: 3.5 out of 5.

Get Waves

Get instant coolness to your work by adding some waves! Few clicks and job done! Possibilities here are endless, but there is one downfall- you may spend a lot of time just generating more waves and not be able to choose just one! 🙊


My rating:

Rating: 5 out of 5.

Confetti

Select a shape inside a frame, tick some options and choose number of rows and columns… ta-daaah! Cool background done! Then you can change colour of some shapes (or not) People will think you’ve spend ages on it.


My rating:

Rating: 5 out of 5.

Color Palletes

For those wanting a nice colour scheme, but not really good at matching colours (or just not having time to think about it!) This plugin provides you with a huge colour collection! It’s a yes from me!


My rating:

Rating: 5 out of 5.

Pattern Hero

Select one of few objects, choose number of rows and columns and your have you own random pattern. The example below is done with simple shapes, so it may not be breathtaking, but imagine doing a pattern with different illustrations (like humaaans for figma people?)


My rating:

Rating: 3 out of 5.

Your recommendations:

Content Reel

Awesome recommendation by @BeckyFumagall, this plugin is a library full of dummy data, avatars and icons. You can also sign up to personalise your home tab to keep all your favourites in one place for a quick access. I’m definitely gonna use this plugin a lot!

Content Buddy

Another from Becky, this plugin lets you quickly replace text content with a different one. I’m sure it’s useful when your designs have a lot of different text areas.

Font Replacer

The last recommended by Becky. I was excited to try this one out, only to be a little bit disappointed by how it’s working. I was annoyed to have to have a text area selected before opening the plugin, not being able to see how different fonts looks like and then when you replace the font, the plugin closes down by itself… For someone really undecided who likes to try different fonts it is quite time-consuming.

Figma Manager

Thalion‘s recommendation. This plugin lets your organise your personal library of components, colours, texts and effect styles. The downfall is the price- 24$ a year for a personal licence.

Toolabs Design System Manager

Recommended by Namik Ozgur Aydin and I’m so happy to discover this system manager! It’s free and really powerful! The plugin is really intuitive, fast and you can personalise everything to suit your needs. You need to create an account prior to using it.

Autoflow

Gercek’s suggestion. Very good option for any flowcharts. I am definitely gonna use this one now instead of draw.io

What’s your favourite figma plugin?

This list is definitely not exhausted, so if you know a cool plugin that isn’t on this list, please share it with me and I will add it here for others to enjoy it too!

Liked this post? Share:

October reads

I haven’t done the monthly reads for a really long time, but as I’ve recently purchased a kindle ebook reader, and along with new uni year, I have made through quite a lot of good books this past month. I guess they might be worth sharing.

1. Invisible Influence: the hidden forces that shape behaviour by Jonah Berger

This one was on one my unit’s reading list, and Im positively surprised on how good it is! Really good insights on people’s behaviour.

Unfortunately had to give it back to the library quickly, as other student has requested it (which is why I invested in the kindle reader 🙊 )
Definitely will borrow it again in the future though!

2. Inclusive design patterns by Heydon Pickering

If you want to design for EVERYONE in mind, this is the book to read. Nicely written with good examples. Some parts may be a little tiny bit dated, but still very good resource.

I have this one in PDF, so it will stay with me for longer 😈

3. Progressive web apps by Jason Grigsby

The first encounter with this book I had after Work in the Web workshop, when Sam. has gave me the link to it ( thank u Sam!) It was really good to go back to it again (again, it’s on one of the unit’s reading list)
Progressive web apps are the future, so it will only do you good to know something about them.
The book itself is really easy to read. I think I went through it in 2 evenings.

4. Influence, impact, succeed- a practical guide to NLP for work by Dianne Lowther

Got this from amazon books (perks of being a student and having 6 months free prime account). I have learnt a lot about peoples behaviour and how others may impact your decisions. Knowledge like this can not only help you succeed in your goals, but also make you aware of how others may be using said influence on you – for their plans.

Have you read anything lately? Let me know!

Liked this post? Share:

My top tips to stay on top of your life and don’t go crazy

Hello, beautiful people of the internet. How’s the life going?
Mine, as you can probably deduct from lack of posts in the recent months, is very busy, engaging and demanding. New job, second year of uni, very active 4 year old and a global pandemic on top of all that!
But I don’t write that as an excuse or for someone to pat me on the back.

If you’ve ever thought how on Earth I am able to manage working, attending full-time uni and taking care or a child… the truth is- sometimes I don’t. You can’t give 100% of yourself to all of those things at once. (Ok, maybe a Wonder Woman could, but I’m definitely not her.) You need to choose where you need to be most, but sometimes things slips through…
It’s so easy to feel like there is too much going on around, and a cartoony steam will go out of your ears any minute now… Instant access and constant flow of various information adds up to the mix.
And that’s why I’ve written down my go to solutions to reduce stress-load to a minimum. I hope it will be helpful to someone.

Here are my top tips to stay on top of your life and don’t go crazy:

1. Write it down. – Mental load is a real thing. Writing things down helps me reduce the amount of information I need to remember in my head. Whether it’s a shopping list, to do list or some random ideas. Format doesn’t matter, as long as you know where to look for it later on. After years of sticking to my notebook, I switched to Microsoft’s To Do app. It has a lovely interface, is fully customisable and I can share my lists with others if I wish to. If you’re after a nice planning app, I recommend giving it a go!

2. Stop micromanaging. – As a perfectionist and a OCD sufferer, I struggle with this a lot, especially at home. But in all honesty, done is better than perfect. Other people are capable to complete tasks too.

3. Prioritise. – There are only 24 hours in a day. Sometimes you just can’t complete all your tasks. Here is where tip 1 comes in handy. Create a todo list and group them (or underline, highlight etc. You set the rules) by their priority. There are things that needs to be done, are stuff that can wait a day or two.

4. Learn to say no. – My weekly dynamics has changed a lot recently, due to my change of job. As a result, I got into a habit of over-planning my weekends. I’d schedule play dates, meetings with friends, weekly house cleaning, weekly shopping…all into two days. Sunday evening came, and instead of feeling rested and ready for another busy week, I was exhausted!
I learned from my mistakes, and now some weekends are SLOW.

Do you have any tips to stay on track? Share with me!

Liked this post? Share:

Create great websites faster, without writing a single line of CSS

Don’t get me wrong, I ♥ CSS, but it can quickly take most of your coding time. The solution? TailwindCSS.

I’ve discovered it few months ago, when I started my internship, and it didn’t take long for me to fall in love with it.
What’s so good about this framework?

  • first of all, it’s really easy to get started!
  • documentation is great, meaning you don’t have to memorise anything.
  • it has everything you could need straight out of the box,
    but if you do need more,
  • it is fully customisable (also super easy to do so!)

The best options to get started is to install via npm or yarn, but you can also use CDN (just bear in mind this option comes with some limitations).

Long story short on how to understand tailwind: just add a class to your element, and tailwind will compile it to a beautiful CSS!
You have no idea how much time you’ll save by not going back and forth from one file to another, and using short names, like mt-2 or font-semibold. (All of which are in the documentation, so definitely check it out!)
Tailwind also has some lovely animation classes, so all you have to type is animate-pulse, animate-bounce, animate-spin or animate-ping, and call it a day, because your website now has awesome animation that only took seconds of your time!


Bonus stuff from Tailwind, that will make creating new projects a breeze? TAILWIND UI.
Ready made components, that you can use like building blocks.
Access to all of them is, unfortunately, paid but you can use some of them for free here.

Have you ever heard of Tailwind? Maybe you already used it in any of your projects? Or perhaps there is another CSS framework you really like?
Let me know!

KAT♥

Liked this post? Share:
« Older posts Newer posts »

© 2021 KAT CODES

Theme by Anders NorenUp ↑