Everything you need to know about styling in React

In this article, we will discuss various different ways to style web applications in React. Choosing the best one depends on needs of your project and type of your application. With that being said, we’ll tell you pros and cons of every approach.

Inline styles

let’s start with the most straightforward approach. This way, you don’t have to create classes or other CSS rules in a separate CSS file. Also, it can help you avoid unnecessary cluttering of global name space for classes.

Styles applied this way have a higher precedence than doing it via classes. This is the same principle as in HTML.

As you may know, React applications are laid out in JSX, which looks like HTML, but it’s actually JavaScript. For this reason, inline styles applied as objects with key-property pairs, where keys are CSS properties and values are CSS values. Like so:

{backgroundColor: “red”}

We can not use the ‘background-color’ syntax like we do in CSS. And because this is a JavaScript object, the value needs to be a string. And the ‘background-color’ property is merged together and written in camelCase.

Inline classes have many advantages, they are easy to read and write. For example, it can be a solid solution for building a prototype. However, as your application and codebase grows in size, inline styles can be difficult to maintain. Also, it does not support essential CSS features like media queries, pseudo classes and other advanced syntax of CSS.

External CSS stylesheets

The standard way to customize React elements’ appearance is to use external CSS stylesheets. This is fine if you’re uncomfortable writing CSS classes in JavaScript, but want to keep things simple. Advantage of using external CSS stylesheet is that you can write CSS styles using a familiar syntax, including pseudo classes and media rules.

However, defining all the CSS classes and rules in one file can be difficult, because you have to come up with unique class names.

External styled-components library

It is a common trend to style React components in JavaScript. The most popular solution is to use external styled-components library.

It combines the best features of both inline styles and external stylesheets. You can write CSS using traditional syntax and store them in each component individually. A great feature is that classname values defined via styled-components are scoped to the component where they are defined. This way, you don’t have to come up with many unique class names.

Also, great feature of `styled-components’ is that you write CSS in JavaScript, but can still use pseudo classes, media rules and similar special CSS syntax.

Even more impressively, this library can be used to create custom styled components. You just define the styles and store them in a variable. Then you can reference that variable in JSX and it will be just like a custom component.

Conditional styling

The great thing about React is that it’s all JavaScript. Even JSX, which looks like HTML, is just a syntax sugar to write JavaScript code. Therefore it allows you to embed dynamic expression within what looks like markup of your page.

You can use this feature to define a React conditional className or apply inline styles conditionally. This is a powerful feature to dynamically change the appearance of your component. Look at websites like SimpleFrontEnd, which contains many React guides.

For example, you can take user’s input, like value of a checkbox element on your website. You can control value of the input from the state, and customize the appearance of your application depending on this state. For example, ticking a checkbox could turn on a dark mode. You simply set the conditional styling to make backgrounds dark and text light colors. And removing selection of the checkbox could remove dark mode.

Possibilities for customization of elements are endless.

Conditional styling is only possible thanks to virtual DOM.

You can’t say that you understand React unless you have a thorough knowledge of virtual DOM and how rendering works in React.

This means understanding all the lifecycle methods, as well as default rendering in React.

Virtual DOM is an important feature of React that makes it possible to have blazing fast web applications.

Dynamic styles

Most conditional styles are based on state values. So it’s Important to know how state works to understand dynamic styles in React.

The state object is treated differently from other objects in React. You can not directly mutate it. You need to use the setState() method to update state in React. This is done to ensure the consistency of state values across entire component tree.

In functional components, you have hooks, which provide an easier syntax for updating the state. In functional components, you define state variables and the functions to update them at the same time. To change the state, all you need to do is call the corresponding updater function.

Selecting DOM elements

Sometimes you need to programmatically style an element. Instead of using CSS or even CSS-in-JS libraries, directly access the element and change its styles.

As we already mentioned, React has its own way of creating elements and maintaining DOM. The elements we define in JSX are React elements, even if they look like common HTML elements, like <div>. They are still React elements, and you can not use the standard vanilla JavaScript methods like getElementById() to work with these elements. Read this guide to learn how to implement getElementById in React.

In general, React does not recommend working with elements directly. In case you’re certain that it is necessary, you can create a ref to store reference to React element.

The ability to use Javascript also allows you to get query params from the URL in React.

Conclusion

In this article, we discussed three different ways to customize the appearance of React web applications. Choosing the best one depends on circumstances of your project. Also, this blog post discusses how to apply conditional className values. We didn’t have time to go over that.

 

JavaScript concepts you need to know to get started with React

Many beginners don’t realize that React is JavaScript library. It’s not a different language, and syntax differences are only cosmetic, so it’s easier to write web apps with React. Under the hood, all of the code is actually JavaScript.

That is why you need at least a basic knowledge of JavaScript to get started with React. I personally think React makes much more sense when you understand JavaScript on a deeper level, but that’s neither here nor there. If you are looking for the bare minimum of JavaScript you need to know, you’ve come to the right place.

Fundamental JavaScript concepts like variables and different types of values are obviously needed, so I won’t even mention them. Instead, I will talk about often misunderstood JavaScript features that are particularly important when developing apps with React.

JavaScript functions and ES6

Component reusability is a foundational concept in React. In this library, components can be of two types – functions and classes. Since the introduction of hooks, functions became the preferred way to write components in React. They have an easier syntax and also they are easier to read. Therefore you absolutely need to understand function declarations, and specifically how arrow functions work in React.

Event handlers, as usual, are also functions, so that’s another reason you need to know JavaScript functions really well.

One important thing about functional components is that they return JSX code. Normally, functions in JavaScript must return a valid value, so why do they return something that looks like HTML?

See, JSX is a template language for React. It may look like HTML, but that’s only to simplify building layouts with React. In reality, JSX is translated to calls to React’s top level API, like React.createElement(). Therefore it is 100% JavaScript. This fact gives React developers the freedom to embed dynamic expressions inside their JSX code and thus build interactive apps with React.

It’s also important to note that the names for functional components are usually capitalized. This is to distinguish components from normal elements, which look and work identical to their counterparts in HTML. For example, you can invoke the same <h1>, <p>, and other elements in React like you do in HTML.

But don’t get confused – both normal elements and custom components are actually JavaScript. Many libraries even provide custom components that allow you to declaratively perform features like redirect users to another page on button click.

Arrow functions are even shorter and have easier syntax. They are often used to define simple presentational components. Knowing the syntax to write arrow functions can be an important instrument for your growth in React.

Template literals

This relatively new JavaScript feature can be very useful in React. Instead of writing static strings, template literals allow you to create dynamic strings. Or at least strings with dynamic parts. This can be invaluable for setting conditional className values, conditional styles, and much more. You can also use template literals as a readable way to push separate strings together.

Template literals are marked by back ticks. If you want to combine a static and dynamic strong, or two dynamic strings, you can simply put them inside template literals. You do need to precede dynamic parts with a dollar sign ($) and curly braces. So a dynamic className value would look something like this:

<div className=`black ${border}`></div>

In this example, the ‘black’ string value will be always applied. The ‘border’ className is interpreted dynamically. Whatever the value of border variable is, it will take place of the variable. Note that you need dollar and curly braces to include this variable.

You can put anything between curly braces. It doesn’t have to be a variable. You can also put ternary operator to conditionally determine the className value.

React is main library for building interactive user interfaces, and template literals are one of the best features to implement dynamic features. This guide goes into great detail on doing string interpolation in React.

Logical operators

Once again, we use React for its dynamic features. Features like dynamic rendering and conditional styles require dynamic JavaScript features. Considering that JSX does not allow you to embed if/else or switch or any other JavaScript statements that require multiple lines of code, simple solutions like && logical operator or || logical operator come in handy. Like ternary operators, you can use them to do simple conditional rendering or any other dynamic feature.

Behavior of logical operators is quite confusing and difficult to understand. Make sure to carefully study how && logical operator works. Same for || logical operator.

AND logical connector checks if the first expression is true. If it is, then the logical operator proceeds to run the second expression. This could be useful if you want to invoke a component only if X condition is true.

These operators help keep your JavaScript and JSX code easy to follow.

JavaScript methods

JSX allows you to embed dynamic expressions into your component. However, you can not use multi-line statements like if or else. You can technically do these things outside of JSX, and then embed variable inside your JSX. But much more commonly you use JavaScript methods like map() and filter() to create elements and components based on data.

In practice, this is very useful as you will often receive data from API structured as an array of objects. map() takes values from each objects and transforms them into elements and components.

You will use these methods all the time. I recommend you practice all the time and if you get stuck, read React guides with examples.

Destructuring and Spread Operator

Essential features in React use destructuring. For example, the useState hook returns two values. You will need to destructure them to store the state variable and updater function in two different variables. Similarly, you can use spread operator when dealing with props, another essential feature in React.

 

Developing apps with vs without JSX

React is a lightweight library that allows us to build very fast applications. Development process is straightforward, but there are multiple ways to go about it. You can use React’s top-level API, like the createElement() method, or make use of React’s templating language JSX. The second option leads to simpler development process. JSX also makes it easy to compose complex component trees.

Now let’s get to the point and discuss advantages and disadvantages of each approach.

Building apps with JSX

If you’ve ever looked at a React component code, you have probably noticed HTML-like portion that defines structure of the component. In many ways, JSX looks like HTML. Most HTML elements also exist in JSX, and function almost the exact way you would expect. But it’s important to remember that React components are written entirely in JavaScript. JSX is only a syntax sugar that looks like HTML. It relies on familiarity with HTML code to simplify the development process.

JSX also gives you the ability to embed dynamic code in structure of your app. This isn’t exclusive to JSX, and you can do the same without it. But React makes it readable and easy to follow. You only need to wrap dynamic expressions with curly braces and React will interpret it as a JavaScript expression. One limitation is that you can not embed statements that take multiple lines. Specifically, you can not use for loops, if/else, switch, and similar complex statements inside JSX. You can, however, use alternative methods like map() or forEach() to accomplish the same.

Most importantly, JSX supports ternary operators. These are powerful little tools to implement dynamic features in React. If you want to dynamically render a component or an element, you can simply embed a ternary operator that checks a condition and returns a component if it is true. You can even specify what to render if the condition is false. Or simply render null – nothing.

Similarly, you can use a ternary operator to conditionally apply styles in React. JSX supports inline styles similar to HTML, except inline styles have to be formatted as a JavaScript object. CSS properties and values need to correspond with JavaScript object and values. Dashes in property names are eliminated and names are camelCased. Similarly, values must be either a string, integer, or a Boolean. String interpolation can be very useful for styling apps with React. This guide will walk you through how to do string interpolation to style elements in React.

You can set conditional styles by using ternary operators to dynamically return values for each property. In case the condition is false, you can add another ternary operator that specifies output styles for another condition. Similar to else if statement in JavaScript.

Perhaps the biggest advantage of JSX is readability. Because code looks so much like HTML, you can easily write your own components and also understand others’ code. In terms of syntax, there are minor differences between JSX and HTML. Namely, names of attributes change. Class attribute in HTML becomes className in JSX. This is necessary because class is a reserved word in JavaScript. Similarly, the ‘for’ attribute of labels becomes ‘htmlFor’ in JSX. Once again, this is necessary to make sure that when compiled into JavaScript, there’s no mixup between the ‘for’ attribute and for loop.

Also, React has a rule that a component can not return multiple elements. You can work around this by wrapping all of the elements in a single <div> container.

React without JSX

You can technically build React components without using JSX. In some cases, it is even advised to build apps this way. For example, when you want to skip setting up compilation in your environment.

There is only one method to create elements in React – React.createElement(). Invoking elements and components in JSX is easy, but it’s ultimately translated to top-level API, mainly the createElement method. You can bypass the compilation and write components using React.createElement(). If your component has many elements, you may need to make multiple nested calls to this method to create a component. For this reason, top-level API is not really suitable for building complex apps in React. Most developers use JSX and we highly recommend you do too.

If you don’t want to, you can create a shorthand for React.createElement method. For example, store the method in a variable, and call that variable. The method takes three arguments – the type of the element you want to create (‘div’, for example), its props, and its contents.

In summary, JSX is just a syntax sugar that replaces calls to createElement() method. Once React apps reach a certain scale, they are much easier to maintain using JSX. Especially when you need to set value on input change in React.

To use these methods, you only need to install React and import it in the file. Top-level API also gives you interface for building class components with React. These types of components need to be instances of React.Component prototype.

Building apps with vs without JSX

There are advantages to both. JSX provides simplicity and familiar development experience. Structuring your app with JSX is practically the same as doing so with HTML. Still, it doesn’t change the fact that JSX is an additional layer of abstraction that needs to be compiled into React top-level API. JSX also has some peculiarities, like having to use className instead of class.

Developing React apps without JSX means bypassing the step of compilation. So if you’re setting up your own environment, that could be advantageous. But the code gets complicated really fast. If you’re building complex structures, multiple nested createElement() methods may be difficult to follow.

 

Cruising with friends – everything you need to know

Cruises are fun for everyone, but especially group of friends who want to spend a vacation together. Ships have so many facilities and activities that everyone in the group of friends can surely find something exciting to do.

Getting on board

Arrange for your group to meet up at least two hours before departure. This will give you plenty of time to make sure everyone is ready for the trip. When the time comes to board, your friend group will be one of the first in the queue and get on board fairly quickly. Make sure all your friends can handle their carry on bags. Offer help to those who can’t.

As soon as you’re on board, unpack your swimsuits and jump into the pool! So make sure to pack swimsuits in a way that they are easily accessible in your carry on. Me and my friends love playing volleyball in the water. There are also floaties so you can chill and sunbathe after getting tired.

Don’t forget to buy an international eSIM to make sure you are connected while at sea. Cruise ships usually have WiFi. You can use it to download videos or any task that requires a lot of bandwidth. But still have some cellular connection just in case wifi does not reach some corners of the ship.

Getting most out of your cruise

When going as group of friends, you can have a lot of fun without even leaving the cruise ship. Still, you can have even more adventures if your ship stops at interesting ports. You should definitely take the opportunity and explore these destinations together. Last summer our cruise stopped at various Greek islands. Exploring the nature together was one of the highlights of the trip. Not to mention picturesque views!

Sometimes cruise operators will also offer organized tours at places where they stop. I recommend to book these to avoid the hassle of planning the trip yourself. But book early or you might find that tours are sold out. Most of these are day trips. Its probably best to go out early in the morning, when everyone is full of energy.

How to avoid motion sickness

If some of your friends are likely to have bad reaction to motions of the boat, plan ahead and consult with a doctor. In most cases, there is a medicine to relieve some of the worst reactions. Travel Calm is good and I always have some with me to make sure everyone’s having a good time and no one misses group activities.

Packing fun extras

In addition to your personal wardrobes, it can be a lot of fun to pack group costumes, so your clique can stand out with original outfits. It can be a conversation starter and help you make even more friends on board. I’ve seen some people wear cruise t-shirts for group of friends, and it looked like they were having fun. Me and my friends are definitely planning to get them before we go on a cruise.

 

Going on a family cruise

Parents on family vacations rarely get to relax. There’s always something to arrange, whether it is accommodation or transport from one location to another. Except for family cruise vacations. With diverse facilities and activities to keep children busy, these offer parents rare opportunity to sit back and do nothing. Not to mention the fact that cruises are transport and destination rolled into one. In summary, cruises combine everything you love about relaxing vacations.

Everything is taken care of as soon as you step on a cruise. Food is plentiful, and you can choose from various dining situations to find something that’s perfect for your needs. Activities are already planned and happening, your kids just have to choose one. All of the activities are specifically designed for maximum fun and engagement, so a lot of the time, parents can sit back and enjoy vacation as a couple. All the while, you get to travel and explore new places. Many cruises will take you to destinations that are great for a family. In our case, cruise took us to various port cities in Italy, and we thoroughly enjoyed everything – from Pisa to Rome. All in all, it isn’t a surprise that cruises are a huge hit with families.

What you need to know about cruising as a family

Cruises in general are good choice for families. However, some operators are more aligned with families’ needs than others. So you need to pick an operation that provides facilities and activities suited for a family. Our kids loved Camp Ocean, a cruise ship that is packed with water activities for kids of all ages. Our kids were aged 4 to 10, but even teenagers seemed to be having fun there.

Choose your room wisely

At first, we thought that any room would do. After all, you only need to go back to your room after enjoying everything onboard. This couldn’t be further from the truth. I found that your choice of rooms can make or break your cruising experience.

Good cruise ships offer options with varying space and facilities. Cheapest rooms are not usually the best. Most ships have balcony rooms, which are larger and more practical if you have kids. Having a balcony also allows you to enjoy some fresh air without leaving your room. Personally for me, its important to not feel claustrophobic in a room. Without a balcony, I’d have to go a long way to access fresh air.

Also when choosing a room, you need to consider its placement on the ship. If you are afraid of getting seasick, choose rooms located in the middle of the ship, as they tend to feel ‘rocking’ effects the least. If you think you or your kids will have trouble with seasickness, consider booking a cruise that frequently stops at ports and doesn’t leave for few days. This could give you a nice break from being on the sea all the time.

Finally, you need to pack clothes. Swimsuits are a must. Its also a good idea to pack casual clothes as well as more official ones. And finally, it doesn’t hurt to have cruise t-shirts for family to celebrate your time there.

 

Spending honeymoon on a cruise ship – do’s and don’ts

When you get married, it’s a tradition to go somewhere special with your special person. Some people prefer mountains, others prefer vibrant cities with character, others prefer historical cities like Rome… In todays article, we will discuss a destination that may seem somewhat unusual for honeymooners. We will talk about spending your first holiday as a couple on a cruise.

Is it a good idea?

As much as I love cruises, I have to admit they are not for everyone. They are like small resort ecosystems. Good cruise ships have everything you could possibly need, but some people may be uncomfortable spending several days at sea on one ship. But maybe you’ve gone on a cruise before as a couple, and know that you will like it. In that case, cruise can be an ideal destination for you and your significant other.

How to prepare for a cruise?

Your packing list for a cruise will depend on several factors – from cruise destination to duration. For example, if your cruise is going to stop at several ports in Europe, then it’s a good idea to bring passports, so you can get off the boat and explore local places. In 2020 our cruise ship stopped for a day at Ostia, which is really close to Rome. I had an amazing time there, even if it only for a day.

Next, you need to arrange your finances. If you’re going to be using credit cards, make sure you communicate with your bank that you will be spending money in specific currency, and buy that currency, so you don’t have to spend exorbitant fees. Or you can spend cash money. In that case, you also need to plan ahead of time and order sufficient amount of foreign currency from your bank. I don’t recommend exchanging money at the destination.

Finally, let’s talk about items you need to pack to make sure you have good experience.

How to make a packing list

When going on a cruise, you need to unpack only once – as your hotel is also your transport. Also there are lots of cleaning facilities on board, so you can stick to your essentials and not worry about laundry.

Most cruise ships have lots of water features, like pools and hot tubs. You will need a swimsuit to enjoy all these. Maybe you can pack two pairs to have options.

As for your clothes, it depends on type of cruise and activities you plan to engage in. Some cruises have more casual dress codes and activities to go with it. Other cruises may have casual, but also more serious events, so you will need a suit or appropriate dress.

In any case, its probably a good idea to take clothes you are comfortable in, and at least few business casual pieces of clothing.

You can also get cruise t shirts for couples to add a bit of flare to your adventure. These will certainly catch others’ attention, and portray that you are available to make friends and have maximum fun.