How to style React apps conditionally

React developers often use conditional styling and className values to build interactive web applications in React. I decided to write this guide to teach you how to apply styles and className values based on a condition and dynamically change the appearance of web application. We will explore different options for applying conditional styles and className values.

Inline styles in React

JSX is a templating language for React. It looks like HTML. In a lot of ways, it works like HTML as well. For example, JSX allows you to set inline styles. However, JSX is still JavaScript, so you can use features like a ternary operator to implement dynamic features. In this case, we can use a ternary operator to set inline styles.

One more detail is that you need to use curly braces {} to embed a JavaScript expression inside JSX code. Applying a conditional style in JSX would look something like this:

`<div style={{border: “2px solid black”}}>..contents</div>`

There are few things to note here. First and most important is that styles are stored as key-value pairs in the object. Therefore you need to follow the rules of JavaScript object – property names can not have white spaces or symbols. Some CSS styles are multiple words, so what happens then? Answer: you simply combine these CSS styles into one word. The ‘background-color’ CSS property will be ‘backgroundColor’ property in React. Learn more about that here:

https://simplefrontend.com/set-conditional-classname-in-react/ .

Second, you probably notice double curly braces and wonder why that is. To put it simply, the outer pair of curly braces tells JSX to interpret the following values as a JavaScript expression. The inner pair of curly braces simply opens and closes a JavaScript object.

Conditional styles in React

Unlike normal HTML, we use the className attribute in JSX. We don’t write class because it is a reserved word in JavaScript.

Unlike Vue, React does not have a built-in system for applying conditional styles. We use ternary operator to determine a className value based on a state variable.

State usually holds values that might change as the result of user interaction. So if you have a React web application, you can offer a dark / light mode feature. In that case, you are going to store user’s current choice in the state. If the user currently chooses dark, then the mode state variable would be ‘black’.

Ultimately, dark and light modes are all about appearances. Dark mode is a white text against dark background, and light mode is the opposite. So you would have one of two className values depending on current value of the mode variable.

In JSX, that would look something like this:

`<div className={mode === “dark” ? “darkMode” : “lightMode”}></div>

Once again, we use curly braces to embed a JavaScript expression. Then we use a simple ternary operator to check if current value of the mode state variable equals ‘dark’ string. If it does, we will apply the darkMode className value. If not, we will add lightMode.

Then you can go to CSS file to define these styles like you would in a normal HTML application.

Three essential concepts to master React

Once upon a time, users had to refresh pages to see new posts and notifications on social media. The same for receiving any kind of updates. No one really thought about it, but Facebook realized there was a room for improvement. They launched React and web development was never the same again. Thanks to React, UX has dramatically improved and users set higher expectations every year.

These days, React is the most popular library for building interactive user interfaces. In this article, we will look at most important concepts in React.

Virtual DOM

React maintains a shadow copy of the DOM. Data displayed on the page is stored in the state and props. Whenever any data changes, React calls the render() method to update the page.

Virtual DOM is very efficient, so it can afford to update the entire component tree. Then React compares virtual DOM with the real DOM and settles differences. This ensures efficiency of the web application. It also ensures that web applications always display the most recent updates.

State, props, single-way data flow

In React, state is the object that stores current ‘status’ of the component. For example, if a new post needs to be displayed, the id of the new post would be added to the state. As you know, changes in the state (and props) also triggers update of the page.

State is often used for dynamic functionalities. For example, dynamic rendering of certain elements or components. State values are also used to conditionally style elements using inline styles or className values.

React recommends to store state data in the component at the top of the tree. This is called a ‘single source of truth’. Every component in a web application should receive data from the main parent component.

Finally, this brings us to props. This is how parent component passes data down to children components. In JSX, you can define props as simple custom attributes on React elements and custom components. Props can be passed from parent components to children, not the other way round. This is called single-way data flow.

JSX

React comes with a custom templating language JSX. It looks like HTML, but JSX is actually JavaScript. This template language allows you to build components, which are essentially small parts of a website. JSX defines what the component should look like and what elements it contains.

Other front-end frameworks like Angular require a separation of logic and presentation. JSX combines presentation and logic. JavaScript expressions can be easily embedded. To do this, you need to wrap JavaScript expressions in curly braces.

You can embed JavaScript expression as prop or attribute values. You can also embed them as contents of JSX elements. React developers often use the map() method to create React elements and components by looping over objects in the array in React.

In JSX, you can conditionally display error messages, or even hide entire components depending on state values. You can’t use getElementById() method, but you can use refs to the same effect. SimpleFrontEnd had a great article on using refs to scroll to a specific element in JSX:

https://simplefrontend.com/react-scroll-to-bottom/.

123

Once upon a time, users had to refresh pages to see new posts and notifications on social media. The same for receiving any kind of updates. No one really thought about it, but Facebook realized there was a room for improvement. They launched React and web development was never the same again. Thanks to React, UX has dramatically improved and users set higher expectations every year.

These days, React is the most popular library for building interactive user interfaces. In this article, we will look at most important concepts in React.

Virtual DOM

React maintains a shadow copy of the DOM. Data displayed on the page is stored in the state and props. Whenever any data changes, React calls the render() method to update the page.

Virtual DOM’s best feature is the efficiency. Virtual DOM updates the entire component tree. Then React compares virtual DOM with the real DOM and settles differences. This ensures efficiency of the web application. It also ensures that web applications always display the most recent updates.

State, props, single-way data flow

In React, state is the object that stores current ‘status’ of the component. For example, if a new post needs to be displayed, the id of the new post would be added to the state. As you know, changes in the state (and props) also triggers update of the page.

State is often used for dynamic functionalities. For example, dynamic rendering of certain elements or components. State values are also used to conditionally style elements using inline styles or className values.

React recommends to store state data in the component at the top of the tree. This is called a ‘single source of truth’. Every component in a web application should receive data from the main parent component.

Finally, this brings us to props. This is how parent component passes data down to children components. In JSX, you can define props as simple custom attributes on React elements and custom components. Props can be passed from parent components to children, not the other way round. This is called single-way data flow.

JSX

React comes with a custom templating language JSX. It looks like HTML, but JSX is actually JavaScript. This template language allows you to build components, which are essentially small parts of a website. JSX defines what the component should look like and what elements it contains.

Other front-end frameworks like Angular require a separation of logic and presentation. JSX combines presentation and logic. JavaScript expressions can be easily embedded. To do this, you need to wrap JavaScript expressions in curly braces.

You can embed JavaScript expression as prop or attribute values. You can also embed them as contents of JSX elements. React developers often use the map() method to create React elements and components by looping over objects in the array in React.

In JSX, you can conditionally display error messages, or even hide entire components depending on state values.

Every front end developer should have a blog – my opinion

The most common problem of beginner front-end developers is that they don’t have online presence. Having a strong portfolio is only a part of that process. A blog can be a great tool for making yourself known and noticed on the internet. If you plan to become a contractor or freelancer, it can be a source of clients for you.

I personally ran a web development blog for 10 years, and I can say it has been one of the best decisions for my career. Let’s go over few reasons why blogging is good for your development as a web developer and obviously for the community as well.

Opportunity to learn

You don’t have to be an expert to start a front-end development blog. Everyone has expertise in certain area of front-end development. And in case you don’t think you are knowledgeable about anything, even better – it could be an opportunity to learn.

For instance, this blog post on SimpleFrontEnd about working with forms could be a great learning opportunity for the person writing it: https://simplefrontend.com/clear-form-after-submit-in-react/ .

There’s a saying that you can only truly know something if you can explain it to others in simple words. Blogging is an easy way to explain things you think you know. If it turns out that you’re not as much of an expert as you thought, then writing about it will be an opportunity to gain an in-depth knowledge.

More importantly, keeping a blog can be an opportunity to learn writing as well. It is a useful skill because web developers not only have to write code, but also comments for one another.

Stay up to date on programming trends and technologies

Blogging about front-end development is a great way to stay updated on latest changes in your technology. It can also be an opportunity to explore other tech stacks and see if there’s anything else for your application.

Sometimes you will learn a new language and have recruiters reach out to you.

Keep it focused

If you want people to follow your blog, write about one topic consistently. The focus of your blog can be very narrow, like one specific front-end framework. You could focus on React, for example. Alternatively, you can dedicate your blog to front-end development in general.

Be consistent

If you decide to publish weekly blog posts, stick with that plan. There is nothing more frustrating than expecting a new blog post and not getting it. If you anticipate that certain time will be difficult for you to write, then write in advance.

Writing technical tutorials in advance also gives you time to proofread them before publishing. It’s a bad idea to write something the day you plan on publishing it. It’s much better to proofread it the next day, or even three days later, to look at it with a fresh perspective.

How to start a front-end developer career

Front-end developers create website interfaces that we interact with every day. There are thousands of businesses with their own front-end development teams, so there’s no shortage of vacancies for front—end developers. However, there is a shortage of qualified front-end developers who can write clean, error-free code. In this article, we will discuss how to start working as a front-end developer in 2022.

Learn necessary skills

Many companies are expecting front-end developers to have a college education, but majority of companies will hire you without one. One main important prerequisite is that you must demonstrate a strong knowledge of necessary skills.

To get a basic front-end developer job, you need to be proficient in three programming languages: HTML, CSS and JavaScript.

You can start learning via online courses, go to bootcamp or even hire a developer to mentor you. There are literally thousands of options for learning front-end development.

Practice writing code

Being an effective and efficient web developer comes down to writing error-free code. Debugging and fixing errors can take too much time. You can achieve mastery of any programming language by practicing it.

HTML is fairly easy, but CSS and especially JavaScript require many hours of practice to fully master.

Gain a competitive edge

Front-end development is a lucrative career, which means that there are a lot of candidates competing for junior positions. Starting a job as a junior developer is especially competitive because all employers are looking for experienced front-end development. There are only few positions where companies want to invest time and resources into developing a junior talent.

Having a competitive edge over other junior front-end developers can help you get the job and then advance your career faster than others. For example, it’s a very good idea to specialize in one JavaScript framework like React. You can go even further and learn features of React. For example, concepts like Virtual DOM, rendering, component reusability, or applying conditional className values.

Get experience

Experience doesn’t have to be of working at a full-time job. Start working on your own personal projects or, in ideal scenario, contribute to open-source projects. Becoming a contributor to one of the open-source projects can be prestigious and interviewers will look at it favorably. These projects usually have requirements for maintaining codebase and gradually adding code. Creating these open-source projects is a team effort, and if you’ve successfully established yourself as a member of a team, it means you can become a productive member of their developers team as well.

Create a portfolio

Having a portfolio of projects you worked on can be beneficial. You can show hiring managers the code you wrote and your CSS designs, for example. Needless to say, your portfolio should include the projects you’re most proud of. Creating projects for your portfolio can be an opportunity to practice. It takes time, but a good portfolio can significantly improve your chances of landing a job.