Loop through array of objects in React

Component reusability is one of the cornerstones of building web apps in React. Developers can write the component once and reuse it as many times as they need. Check SimpleFrontEnd for great tutorials on React.

Why we need to loop through array of objects

Often we need to render components based on data received from the API. External data can be formatted in many different ways. Most often, we receive an array of objects. Each object contains information to render a component or element. Most often, we use map(), filter(), or other array methods to return a new array with modified items. And the callback function is used to specify how every item needs to be modified.

However, looping through an array of objects requires some precision. First of all, let’s look at how to import an array of objects from an external source. This is usually done using the useEffect() hook. It’s important to understand how the dependency array works and how useEffect () can replace lifecycle hooks, typically used to perform side-effects in React.

Once you have an array of objects stored in a state variable, you can get to work. You need to create a new array where every item is an element or a component. Methods like map() and filter() are perfect for this purpose. Map() returns a new array made up of transformed components, and filter() does the same except it filters array items as well.

Using map() to loop through array of objects

So, how do you use map() to loop through array of objects in React? You take information contained in objects and use this information as values for props and contents for components.

You can create a new array of elements and components in JSX or outside of it. The latter option is better, because it’s more readable to separate JavaScript logic from JSX as much as possible. It’s better to finish the array transformation and store final result in a variable. Then you can reference that variable inside JSX. Remember to use curly braces to differentiate dynamic expressions from normal content in JSX.

If you do decide to use map() directly in the JSX, you will need to use curly braces. In fact, you might need to use curly braces on multiple levels. For example, you need initial curly braces to embed the initial expression (performing map() on array). Remember that map() callback function usually returns JSX, so you need to use curly braces again when you need to embed values from the object into elements.

There are other things to remember when you use map() to loop over objects in the array. For example, every new component or React element must have a unique id property. This is necessary so React can reliably identify every DOM element.

Technically, you can also use for loops and forEach to loop through an array of objects in React. However, doing this requires more lines of code and the end result simply isn’t as readable as using the map() method. SimpleFrontEnd explores different ways to loop through an array of objects in React.

Create select dropdowns and set their default value in React

Every dynamic React application should give users some way to interact with the app. Most commonly we use standard input fields where users can enter anything. In this article, we will explore how to set up dropdowns so users can choose one of many provided options.

JSX is a templating language for React. In a lot of ways, it works exactly like HTML. Except one big difference – it’s actually JavaScript. Still, it allows you to create elements like <select> the same way you’d create them in standard HTML. At first glance, <select> element in React looks indistinguishable from the same element in HTML. One big difference is that JSX allows you to embed JavaScript expressions. You can do so by using curly braces {} around the JavaScript expression. This is necessary, so React knows what parts are static and which are dynamic.

How to set default value for <Select> elements in React

You can easily select one of the options by default. This is useful if you need to suggest one of the choices.

First, you need to set up a normal <select> in React. This involves multiple routine steps. Create a state variable and the function to update it. Then tie <select> element’s value to the state variable and set an onChange event handler. Then come up with a few options with unique value values. This may sound strange, but the value is an attribute for <option> element in React and HTML. Developers should set it to a unique value.

Next, simply add the defaultValue attribute to the <select> element to set its default value. You need to specify which option is going to be selected by default. To specify this, simply set defaultValue to the value of one of the options.

You can also set a placeholder as the default option. It will allow you to not use a label. Usually, placeholders look better. Check this guide to see a live demo of <select> default value.

There are a number of libraries that provide custom functionality. Even though you don’t need a custom component to set a default value, you might still need it for other advanced features like multi-select.

These custom components accept options as a prop. You create an array of objects with two properties – label and value. Every object describes one option. Then you set options prop on the select element itself.

When dealing with custom components like these, you can set default values the same way you set options. Use the same attribute defaultValue, but this time you need to set it to an object that describes an option that should be the default.

Generally, I wouldn’t recommend using libraries when you don’t need them. However, sometimes building a certain feature takes too long. Still, you might learn something by building it. I’ve learned a lot by looking at interesting libraries and trying to build their features myself.

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.