Follow along my thoughts on technology and other interests of mine

Category: Career in Tech

How to scroll to a certain element in React

Modern web applications can be quite overloaded with content. As a web developer, sometimes you want to help users find exactly what they’re looking for. Users don’t like to scroll long pages, especially on phones. You can use something like table of contents to help users navigate long stretches of text, but there is no table of contents for normal page. If you’re building your web application in React, there’s an easy fix – you can simply use scrollIntoView() method.

In this article, we’ll show you how to scroll to a certain element using the scrollIntoView() method. This way, users can skip straight to the part they’re interested in.

The method should be called on a DOM element.  In JavaScript, typically we use getElementById() to store a reference to certain element in a variable. React has Virtual DOM, so selecting an element works a little differently. In React, we use refs to store DOM elements in a variable.

There are a number of ways to create refs, but for the sake of simplicity, we’ll use the useRef() hook. It is available in all functional components. Simply import the hook from the core React library, create a variable and set the variable to an instance of a useRef() hook. Then set the ref attribute of the React element to the variable name. Now the variable holds a ref (reference) to the DOM element.

Let’s imagine we have a variable box that holds reference to a <div> element. You can simply call box.scrollIntoView() and the scroll position will be set to that <div>.

How to use it to improve the user experience

Often times you want to scroll to a certain element on the page as soon as it loads. In React, you can do that by calling ref.scrollIntoView() in lifecycle methods or the useEffect() hook. If you don’t know how to work with the useEffect() hook, read this tutorial.

Other times you want to scroll down to element after a certain event. Most frequently this is a click event. You can have buttons for different parts of the page. Users can click these buttons and will be taken immediately to respective elements. This saves a lot of time and will inspire users to come back and use your website again.

Scroll to bottom

Sometimes you want to scroll not to a specific element, but to the bottom of the page. There isn’t a method specifically for scrolling to the bottom. However, you can call scrollIntoView() on the main container of the page and provide it an options object as an argument. Nick at SimpleFrontEnd has written an excellent article with an example of scroll to bottom feature in React: .

In the options, you can use the block argument to specify which end of the element you want to scroll into view. You can set it to “end” to scroll to the bottom of the element. Because the element wraps around everything on the page, this will also scroll to the bottom of the page.

Different ways to design React web applications

Every front-end developer knows about the normal ways to design a web application. Connect external stylesheet with an HTML file, apply classes and that’s it. However, many front-end developers don’t know that there are many other ways to customize the appearance of a web application built in React.

Design web application via external stylesheet

This is the standard approach for styling web applications in CSS. Linking React components with CSS files is pretty similar to how we do it in HTML. First we create a CSS stylesheet, write required CSS rules, and use the import statement to make it available in the React component.

Linking CSS files with React components is good if you’re already familiar with the process of writing CSS rules for styling web applications. Most web developers have been using this syntax for years.

Using inline styles

Many React developers will advise against using inline styles, but there are certain use cases where they are useful. For example, if you are building a prototype of a web application, or just a small application.

In React, inline styles are written as JavaScript objects. And you probably know that React elements are written in JSX. You can set the style attribute of React elements to a JavaScript objects where keys represent CSS properties, and values represent CSS values. For example, something like this:

{backgroundColor: “red”}

As you can see, instead of writing CSS property as you would in a separate stylesheet (‘background-color’), we write it as backgroundColor – two words pushed together and camelCased. Also, the value of this property needs to be a string or other valid JavaScript value.

One final detail is that in order to evaluate JavaScript objects as such inside JSX, you need to wrap JavaScript code with an additional pair of curly braces.

Conditional styling

A great thing about React web applications is that you can dynamically customize the appearance of each element. For example, if a user enters wrong value into the email field, change the color of input element to red and highlight the error.

In React, you can use expressions like ternary operators to set up a condition and dynamically return one class value or another. This is the best approach for setting an inline expression that generates a dynamic class value. The process is better described in this tutorial on setting conditional className values in React.

Alternatively, you can create a condition outside of JSX. This is better, because you can’t use statements like if, case or a for loop within JSX. You can set a much more complex condition outside of it.

External libraries

React community has created various libraries for handling common styling tasks in React. For instance, the classnames package provides a function of the same name, used for dynamically applying class values.

There is also a popular styled-components package, which can help you create local CSS rules for components. It is commonly used in development of large scale web applications. You will often find that the knowledge of this package is necessary to get a job.


Most important concepts in React

React is a great library for building interactive interfaces. It has a fairly easy learning curve, but often beginners overlook certain important concepts. In this article, I want to discuss which are the most important concepts in React library.

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.

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.

Controlled components

Understanding the concept of controlled components is essential, even for beginner developers. In short, these are components that get their value from the state. It is a typical 2-way binding, where typing into a controlled input elements updates the state value, which then updates value in the input.

If you’re coming from Vue background, you need to pay attention to this. In Vue, handling the value of input elements is very different than it is in React.

Mutating the state

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

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.

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.

Where to learn skills for front-end development

Front-end development means building websites with beautiful design and sometimes dynamic features. Most of the complex web applications you visit every day – Facebook, Netflix and Disney plus are created more or less the same principles.

There are three main skills to developing websites – CSS, HTML and JavaScript. HTML is used for writing markup. In other words, creating elements to define a structure for the page. CSS is used for customizing the appearance of elements created with HTML. By extension, it can be used to design the entire website. Lastly, JavaScript is used for implementing dynamic features of a web application. For example, collecting user data, doing dynamic analysis, loading external data and other use cases for implementing business logic.

Learning HTML and CSS

Let’s discuss learning HTML and CSS. HTML is considered to be simpler of the two, while CSS appears simple, it’s complex.

For starters, you should attempt to learn CSS and HTML on freeCodeCamp, which is a great free resource for learning front-end development. It has all the necessary tools to help you learn these skills. You can practice writing actual HTML and CSS code, and solve actual challenges like building a simple static website.

Free resources are good place to start because you can get started without too much investment. Another great website is Codecademy, which explains CSS and HTML concepts in detail and takes you through the steps of learning as you write the code.

Learning Javascript

Next, it’s time to learn JavaScript. In this case, freeCodeCamp is a good place to start. It can give you a solid knowledge of JavaScript to get started. In addition to that, you can read free online book like ‘Eloquent JavaScript’, which is recognized as one of the great resources for learning JavaScript. There are dozens of other courses that teach JavaScript, so it’s hard to choose the right one.

Learning front-end frameworks

In case you don’t know, modern web applications are developed with JavaScript front-end frameworks like React or Angular. These frameworks provide a foundation for performing common web development tasks. You can simplify your life by using them.

To maximize your chances of landing a job, it’s preferable if you have a specialization in one of the frameworks. There are many great courses and websites that aim to teach you programming. Sometimes these websites and even courses have free and paid versions, so you can try it out before paying.

Front-end masters is considered to be one of the best resources for learning front-end development. They offer discounts in some cases.

Learn from documentation

Once you nail basics of one of these front-end frameworks, you can move on to official documentation of these languages. All three of them – Vue, React and Angular have excellent documentation to teach you programming in these languages.

Written documentation is a bit impersonal, and tutorials may be better if you prefer a personal touch.

© 2023 Fabian Olson's Blog

Theme by Anders NorenUp ↑