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.

 

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.

 

set OnKeyDown on input elements in React

Handling events is one of the most important aspects of building apps in React. You need them to build dynamic applications and interactive features of a web application. In today’s article, we will talk about the onKeyDown event – how to set it on elements and how to handle them.

We often use onKeyDown to run a JavaScript function when users press down a key when they have selected an element. In practice, it is often used with <input> elements. On rare occasions, you can also use it on <div>, <span>, and other elements.

How to set onKeyDown on Elements in React

It’s essentially the same as setting any other prop or attribute. You need to set onKeyDown to a JavaScript function. Don’t forget to use curly braces, which allows you to embed JavaScript expressions in React. Don’t set onKeyDown to an expression that calls the function. Instead, set it to the function itself.

In React, event handlers automatically receive instance of SyntheticEvent as an argument. This is an object that contains information about the element and user input. Developers who want to handle onKeyDown event can access the specific key that was pressed down. This is often a very useful feature, because we need to perform a certain action when user presses a certain key. For example, you might want to allow users to submit their input by clicking ‘Enter’. This way, users can provide input without additional hassle. It’s always difficult to get users to provide their feedback. Allowing them to submit by clicking a certain key is a great feature for your UX.

Access specific pressed down key

To access specific key user pressed down, you need to access key property of the SyntheticEvent instance. Then you can use equality operator to make sure user pressed down a certain key. Use an if condition block to check a JavaScript expression. Then write what you need to do in the condition body. SimpleFrontEnd has a good example where they use this feature in practice.

Let’s look at an example:

let handleKeyDown = (e) => { if (e.key == "M") { console.log("User pressed M")} } };

This is a simple callback function that accepts one argument – e , which stands for SyntheticEvent. You can simply access e.key to access the specific key pressed down by user. In this case, we have set up an if condition to check if user pressed the ‘M’ key. If they did, we output corresponding message to the console.

You should set onKeyDown on <input> elements. Whenever user enters something new, onKeyDown will check keys that were pressed down. If any of those keys match the key specified in the condition, then you can run a function. You can also skip the if condition and simply run a function whenever user presses down any key.

You can also save user inputs whenever user presses Enter. Here’s an example where we use onKeyDown to submit input on enter in React.

 

Importance of having a user-friendly UI

When building websites, companies sometimes pay too much attention to content and not enough attention to website UI. What does UI mean though? It is short for the user interface. In other words, parts and features of the website that the user sees and interacts with. Web developers should always focus on making the website easy to use, easy to understand, and easy to navigate.

If users can not find what they’re looking for, they will get frustrated and leave. Most likely, they will never come back. This is the worst-case scenario for a business, especially one that relies on returning customers. In short, having amazing content means nothing without also having a user-friendly interface.

Does it affect your bottom line?

Yes, user-friendly websites are typically more profitable than those that are not. This is for a number of reasons. If the website or web application makes money primarily from ads, then more engagement means more time spent on the website, which means more ad revenue. Even if you don’t make money from ads, you want users to interact with your website. This allows you to study their habits and notice patterns to further improve your website and optimize it for users.

Important things to remember

Never forget that you (the creators of the website) may be different from your intended audience. For example, you might find it easy to work on a tech website, because you understand technology yourself. However, the people who will come to your website want to learn about technology, so they know very little. It’s important to not confuse them.

New users might not be familiar with the latest trends. Always assume that they’re seeing the website for the first time, and make the website usable for them regardless.

Web developers sometimes live in a bubble where everyone around them understands technology, at least to some extent. But you’d be surprised to find out that 90% of internet users are not good with technology.

Practical tips

If you have a website that is difficult to figure out, include a tutorial that introduces people to the most important pages and features.

Identify which pages are the most troublesome for your users and try to simplify them. For example, I run a small quiz website and a lot of my audience were struggling with the forms they had to fill out. I implemented a number of UI features to fix this.

My website was built in React, so I could easily implement these dynamic features. For example, after users signed up, I would redirect them to a dashboard page and give them access to the admin panel. Here is how to use useNavigate() to redirect users in React.

If the users had to work with the same form over and over, I cleared their inputs after every submission, so they didn’t have to delete their own inputs.

Summary

When building websites or applications, user-friendliness should be your main concern.