Latest Tutorials

Learn about the latest technologies from fellow newline community members!

  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL
  • React
  • Angular
  • Vue
  • Svelte
  • NextJS
  • Redux
  • Apollo
  • Storybook
  • D3
  • Testing Library
  • JavaScript
  • TypeScript
  • Node.js
  • Deno
  • Rust
  • Python
  • GraphQL

How to Use React onClick Events in Class and Functional Components

In this article, we’ll cover the basics of React onClick events and we’ll learn to handle click events in class and functional components. We’ll discuss the differences between JavaScript and React click events, the syntax of event handlers, and binding event handlers to the this keyword. React has many intimidating parts that are harder to grasp for beginners, but the way events are handled in React is simpler and more straight forward than in vanilla JavaScript.  In JS, the behavior is separated from the HTML, so if you want to add an onclick event handler on a button element, you first need to select the DOM element, then you need to attach an event listener with the .addEventListener() method. Inside this method, you can call or define another function that will execute when the event is triggered.  A simpler approach is to assign an onclick event to a DOM element inline, and to call a function that will execute only when the event fires. In this case, you write a bit less code, but you still need to use a method like .getElementById() inside the function, for selecting the element.  When the HTML and JS code are in separate files, finding the right elements and ensuring the correct scope for each function can become quite a challenge.  In React, each component has its own markup and methods, and in most cases, there’s no need to add or remove event listeners. You can simply declare the function to be called inside your component, and immediately call it inside the return() method.  We’ll look at some practical examples and compare the way JS and React handle click events in the next sections of this article. This article will give you an overview of React onClick event handlers their particularities and differences compared to JavaScript event handlers. By the end of the post, you should know how to handle events in both class and functional components, and how to pass parameters to onClick event handlers. This article explains the React onClick event handler and its uses in functional and class components.  To be able to follow the examples, you should be familiar with:  If these concepts are new to you, please take a few minutes to read about JS click events first, and check the React documentation for a short intro to JSX and React.  Just like HTML/JS, React allows you to call functions and perform actions when a user interacts with the app's interface. These interactions fire events, which can be keyboard events, focus events, touch events, click events, and so on. Click events are triggered when an element is clicked, and are defined in React with the event type onClick . This is passed as an attribute to the element that we want to react to the user's action. What happens after the element is clicked is defined with event handlers, which can be browser actions or JS functions.   Although in most cases onClick handlers are used with buttons and links, you can place handlers for click events on any element, including plain text or containers. If we look at the syntax of event handlers, there are two main differences between React and pure JS code. First, React events use camelCase syntax, so instead of writing onclick , we’ll write onClick .  Then, if JavaScript functions are used for performing some action when an HTML element is clicked, the event handler calls the function like this:  In React, the function is called inside curly braces:  This may seem like a small difference, but it’s essential to keep in mind, as calling the function directly in the JSX code means that the value of the function is used in the onClick attribute. So instead of passing a function that can be called every time the user clicks the button, you’re calling it only once, when the component is rendered.  In this case, all other clicks on the button will call the result of the function, so there will be no interaction to see, no action to perform.  Another difference is that in React the event handler onClick can only receive one function, while in the HTML/JS approach, any number of JS functions can be passed to an onclick event handler.  Finally, React events always bubble , while in JavaScript some events - such as onchange for example - do not bubble up. This means that if you have an element or component nested inside a container, and you assign an event handler to the container, when you click the nested element the event will still be captured. This happens even if you don’t directly click the container, because events bubble up to all their parents and ancestors. All modern browsers have event bubbling as their default manner of handling event flows.  A consequence of this behavior in React is that if you want to prevent the default propagation of events, you need to call preventDefault() explicitly. Compared to JS, in React you cannot use return false, so you would have to do something like this:  We’ll look at this behavior more in-depth in the next sections.  Now that you are familiar with the basics, let’s see how event handlers look in class and functional components. For both examples below I’ll use codesandbox.io.  In a functional component, the event handler is passed as an attribute to an element or component. This attribute receives a function that describes what happens when the user interacts with the element.  Like with any other event, if the user clicks the element multiple times, the event is triggered and the function is called multiple times. Let’s see how this looks in practice. I’ll create a new React file in codesandbox.io, with no additional dependencies. You can find the sample code here .  When you run this code, you should see the message ‘Hi there, user!’ logged once in the console. This is the result of <div onClick={greetUser()}> calling the function inside the JSX code. However, if you click the button, the message will log again in the console, because the event calls the greetUser() function defined above.  Now, if the div onClick would also call the function instead of the function result, we should see the greeting message logged in the console also when clicking the text. This would be the result of the event bubbling up to the parent container.  Let’s see if this works correctly. In the code above, remove the () from <div onClick={greetUser}> . Click the text now, and you should see in the console the message ‘Hi there, user!’ logged again.  Moreover, if you click the button now, you should see the message logged twice. This happens because you’re actually triggering two events: one on the button, and one on the div container.  Class components handle events in a similar manner, but there are some small differences. Let’s look at an example:  You can find the sample code for this example here .  Note that the handleClick function is defined outside of the render() method. We can also declare an inline function directly in the onClick attribute, like below:  In this case, clicking either one of the nested components - the paragraph or the button - will log the message in the console. Now let’s see how we can prevent the event bubbling behavior with preventDefault() . Let’s say that instead of logging something in the console, we want to redirect the user to another page when the text is clicked.  Let’s adjust the code like below:  You can find the code for this example here .  I did the following changes: first, I’ve replaced the <p> with an <a> , and added the href=” https://google.com ” attribute. So now if we click the text, we should be redirected to Google’s homepage. At the same time, when clicking the link, the ‘Hi there, user!’ message should be logged in the console, because of the event bubbling behavior explained previously.  To redirect in this case is the default behavior for the <a> tag, so if we add preventDefault() , the redirect shouldn’t happen anymore, but the greeting message should still be logged. Let’s see if this is what happens. First, we need to adjust the handleClick function as follows:  Now if we run the code and click the text, we should see the message logged once in the console. If we click the button, the message will be logged twice.  In this example, the e is called a synthetic even t, and it's a cross-browser wrapper around the browser's native event. It has the same interface as native events, so it can make use of the preventDefault() method, as shown above. The advantage of React's events is that they provide cross-browser compatibility, so a React click event behaves the same across all browsers. In class components, it is good practice to declare the function inside the component, as a method. However, if you want to pass props or state later on to the rendered component, you need to bind the event handling function inside the constructor.  Here’s an example:  It's necessary to bind this inside class components, because they're not bound by default, so if you write <button onClick={greetUser}> , nothing will happen. Try it out, you should get an error that says that greetUser is undefined. Let’s say that instead of logging the message ‘Hi there, user!’ you want to show the user's actual name. You want this to change for every user, so you need a way to pass the name as a parameter to the onClick event handler.  You can do this with an arrow function. In this case, the functional component from our previous example could look like this:  You can find the code for this example here . In the case of class components, we have to bind the event handler to this , as shown before. Our component will therefore become: You can find the code for this example here . React click events are similar to JS events, with a few differences in syntax and propagation behavior. Event handlers such as onClick can be used in both functional and class components, the former being more straight-forward, while the latter requires the binding of the handlers to this . To learn more about React's event system and how to handle user interactions in a React app, check out lesson 10 in our 30 days of React course .

Angular Directives Demystified

Directives are one of the least used features in Angular. They are often overlooked as devs typically tend to put all the logic into components. Lack of a clear understanding of how directives work also contributes to their underuse. In this article, we will learn all about directives, when and how to use them, and look at some useful real-world examples to cement this understanding.The rise of Angular and other similar front-end frameworks has led to a new style of development - Component Driven Development(CDD). In this approach, any given feature is broken down into a set of components that are to be implemented. These components will act together in some way to provide the feature to the user. Since there is a lot of focus on the component as being the primitive or the basic unit of functionality, other ways which the framework provides for adding behaviour tend to get overlooked. Directives are one such feature in Angular. In fact, a glance at Angular's official documentation on directives reveals that Component is actually a subclass that's derived from Directive ! So in effect, you're creating a directive every time you define a new component. Any DOM manipulation logic within your components can most probably be offloaded to a directive. For example, you could use a directive to add behaviour such as drag and drop, or remembering scroll position. This makes directives a great tool for making behaviours reusable and applying them to different parts of your UI. In the upcoming sections, we will learn about the different types of directives, look at appropriate use cases for each type, and understand them better through examples. As we discovered earlier, an Angular Component is a specific type of Directive . It is, in fact, a directive that has its own template. A Directive , on the other hand, does not have a template. We can declare a directive using the @Directive decorator: The selector property represents the CSS selector that identifies this directive inside of a template. You can use different ways of declaring the selector, which influence the way the directive is instantiated: Other, less commonly used selectors are: Directives can also have inputs and outputs specified by the @Input and @Output decorators respectively. You can also use Angular's dependency injection mechanism to inject services through their constructor. The Angular framework makes heavy use of directives to provide a lot of inbuilt functionality. Most Angular template features that we use on a regular basis are based on directives. Let's look at the following example that uses the ngClass directive. Here, we are using the ngClass directive to dynamically switch the CSS class on the text based on the isServiceRunning variable in the component. We can clearly see that ngClass uses an attribute selector to implement its functionality and that it takes an object as its value. This object contains a set of class names as keys, with the values being boolean expressions. From this, we can work out the actual implementation of the ngClass directive - it applies the CSS class in question if the expression evaluates to true . Looking through the source code for the ngClass directive, we can confirm that this is indeed the case. Another very commonly used directive is the ngIf directive. It is used to add and remove elements from the DOM based on the specified conditions. In the above example, the welcome message is either shown or removed, based on the showWelcomeMessage variable. Directives such as ngIf are instantiated with a * in front, which makes them slightly different in terms of their behaviour. Let's look at the different types of directives in the next section. There are three types of directives that you can build in Angular: As discussed earlier, a Component is a specific type of directive, so it has a very similar API and behaviour, with some bits added on. A Component can be declared using the @Component decorator, and takes a config object that is quite similar to the one for the @Directive decorator. It inherits the selector property, which in the case of components is always an element name since the component will be instantiated using its tag in a template. In addition, it includes a number of Component -specific properties: Here's a simple example: This is a component that renders a styled text box with the specified input and emits an event when the value changes. We will not go into greater detail regarding components in this article, as this is quite a vast topic and warrants an article of its own. We will instead focus in-depth on other the other available types of directives. Earlier in the article, we have seen how the ngClass directive works. This is a great example of an 'attribute directive'. This means that it is instantiated using the ngClass attribute on the element in question, with the input value being passed in through the attribute. It is worth noting here that ngClass supports multiple types of values: Apart from these, you can also use an expression that evaluates to a string, array or object. Another built-in attribute directive is the ngStyle directive. This can be used to set particular style attributes on elements dynamically based on calculations or values in your component. In the above example, the font size for the span element is set based on a value from the component. You could use this, for instance, to dynamically scale font size based on the content length. Creating our own Attribute Directive Now that we have seen how to use the built-in directives that Angular provides, let's create our own attribute directive to better understand how they work. A fairly common use case in apps that feature any kind of scrollable content, is remembering scroll position when you navigate away from a page and restoring it when you return. This might sound really complicated and difficult to build, but let's simplify and break it down. Here are the things we need to do: Let's implement the first step and see what that looks like. The ElementRef has been injected into our directive through the constructor. It provides access to the element on which the directive has been applied. A small concession that will simplify the storage of the scroll position is the use of an id on the element. This gives us a unique key to reference the value when storing it in local storage. Now that we have stored the scroll position, let's implement the bit where we retrieve and actually apply it back to the element. There we have it! We've just built a directive that can be used on any scrollable element to help it remember its scroll position. It is easy to see how all this logic could have been crammed into a component and it would work just as well. However, by extracting it into a directive, we have offloaded the responsibility from any component. Another great advantage we have gained is that this new directive can be reused in as many components as we like since we've built it to be as generic as possible. In an earlier section of the article, we have briefly looked at the ngIf directive and how it adds and removes elements from the DOM based on the condition supplied. We had noted that the ngIf directive is instantiated with a * in front, i.e. as *ngIf . Directives that are used in this way are called 'structural directives'. They are so named because they can manipulate the structure of the HTML layout by adding, removing or changing the way elements are laid out. This is immediately clear in the case of the ngIf directive. The * in front is actually 'syntactic sugar' - i.e. the Angular compiler internally converts it into something a bit more elaborate. So if we consider the following example: This is actually shorthand notation for: An alternative to the ngIf directive for when there are multiple choices to make is the ngSwitch . This is not as commonly used as the ngIf but can be quite handy for reducing nesting in your templates. Here is an example that renders different components depending on the status of the todo object. Another indispensable structural directive is the ngFor directive. We use this to loop over arrays and render a fragment of template for each of them. The above example renders an unordered list with a list item for each to-do in the array. The ngFor directive can also provide an index for use inside the loop. When rendering large lists of data which can be manipulated or changed in any way, it can get computationally expensive to re-render large numbers of DOM nodes each time the list changes. For this reason, the ngFor directive takes an optional trackBy input. This needs to be a function that takes two parameters - index and item . The return value of the function should be a unique key that Angular will use to determine if an item needs to be re-rendered. If you're getting your data from an external API, it will most likely come with IDs that you can use for the trackBy function. Creating our own Structural Directive Now that we have seen what Angular has to offer in terms of structural directives, let's try to create our own. It is pretty common within apps to have multiple different types of users with different permission levels. We are often asked to show or hide certain functionality based on user type and so on. Let's build a structural directive that hides an element if the current user is not authorized to see it. So here are the things we need to do: Let's start by creating a directive. Since we are creating a structural directive, we will apply it to any element using the asterisk in front. As we have seen earlier, whenever Angular encounters a directive that starts with * , it wraps the host element in an <ng-template> tag. The template tag is invisible to the DOM. A reference to this template - a TemplateRef - can be injected into our directive via the constructor. In addition, we will need to inject a ViewContainerRef , which is a tool that Angular provides to be able to programmatically instantiate views. Once we have these injected, it is simply a question of using them to implement our functionality. Lo and behold - our directive is ready for action! It can now be reused in place of many repeated lines in our components where we would have called the AuthService and used an ngIf in our templates, thereby providing a much cleaner solution! In this article, we have done a deep dive into the internals of Angular directives. We have learnt about the differences between components and directives and discovered that components are actually just a specific type of directive. We have also learnt about the other types of directives - attribute and structural directives. In addition, we have explored all the different built-in directives of both types that Angular offers. We have tested our understanding of the core concepts by creating our own directives that address real-world use cases. Here's hoping this article has helped clear some of your misgivings about Angular directives and taken you a step closer to being able to use them effectively. Happy coding! 🚀 The Angular documentation on Directives is a great place to start learning about them. The docs around TemplateRef and ViewContainerRef make for good reading to improve your understanding of some of the lesser-known parts of the Angular framework. This article shows a great example of creating a custom structural directive.

Thumbnail Image of Tutorial Angular Directives Demystified

I got a job offer, thanks in a big part to your teaching. They sent a test as part of the interview process, and this was a huge help to implement my own Node server.

This has been a really good investment!

Advance your career with newline Pro.

Only $30 per month for unlimited access to over 60+ books, guides and courses!

Learn More

How to Display Modal Dialog in React with react-modal

In this article, we will learn how to display a modal dialog in React applications using react-modal. We will see how to configure and style modals with it. We will also consider other ways to display modals available in React and when to use each of them.Modal dialogs are a popular way to display information in modern web applications. It is a common task in React applications to display a dialog and you might want to have a good tool for that. React-modal provides a React component that helps to display modals with an overlay. The component provides additional events to control dialog's behavior when opening and closing it. For this article, we assume that you're familiar with React components basics, such as working with component's properties. We will start by adding the react-modal package to our project: The package provides the Modal component that we're going to use. Now, let's display a modal dialog using the Modal component: In this example, we display a simple modal dialog. The dialog can be closed by clicking on the overlay or by hitting the ESC key. The react-modal takes care of positioning the dialog and displaying an overlay. We start by importing the Modal component from react-modal . Everything that goes inside the Modal component will be rendered as a modal dialog. We control the visibility of the dialog with the isOpen state variable. We configure the Modal component with properties: With the Modal component, we can quickly display a modal dialog. Next, we will learn how we can style our modals. The Modal component comes with default styles for modal and overlay. We can change these styles to fit our application's design. The styles can be changed either with inline styling or with CSS classes. By default, the modal will stretch almost to a full screen with a white semi-transparent overlay. Let's change the overlay color and add the animation for a dialog. The modal will also take only enough space to fit the dialog's content: We've provided additional properties for the Modal component here: In the styles.css CSS file we've declared the following styles: The mymodal class defines styles for a modal and the myoverlay class defines styles for an overlay. We've additionally defined the ReactModal__Overlay , ReactModal__Overlay--after-open , and ReactModal__Overlay--before-close classes: These classes will be applied to overlays of all the react-modal modals in our application. We use them to define the animation for our overlay. There's also the global ReactModal__Content class that we can use to define global styling for all the modal dialogs. The react-modal package provides a simple modal dialog component. Using this component you can quickly add modal dialogs to your React application. Here are some alternatives to react-modal and when you might want to use them. If you're using one of the popular UI frameworks , feel free to use components provided by a framework. Popular UI frameworks such as Material UI , Bootstrap , and Semantic UI provide components for modals, alerts, and tooltips. If you need to display a tooltip , check out the react-tooltip package. It provides a component for displaying tooltips with lots of advanced features. If you need maximum flexibility with your modals , check the react-portal package. It provides basic support for modals and you'll be in charge of implementing all the details. In this article, we've learned about displaying modal dialogs in React with the react-modal package. It provides the Modal component that takes care of modal positioning and displaying an overlay. We've also reviewed alternative solutions for displaying modals in React that you might find useful.

How to handle navigation in your app with React Router Link

In this article, we'll explore the navigation possibilities in a React app and we'll take a look at the React Router Link component. We'll discuss: the approach and prerequisites when handling navigation with React Router, why Link is preferred over a simple a tag, and how to implement React Router Link and its variations, NavLink and Redirect.React is an awesome library for single page applications that require fast loading speeds and real-time updates based on user interactions. However, most web applications are multi-page. In non-React apps, the navigation between pages is done through <a> tags. The same can be used in React, but the problem with the these tags is that they create server-side links. This means that whenever you click on the tag to access another page, a new request is sent to the server, and the current page is redirected in the browser to the new page. React Router switches from server-side to client-side routing, so when you click on the Link  component, the app checks the route and loads the requested component without reloading the full page in the browser.  This ensures faster page speeds and a better use of resources, and contributes to a nicer user experience, since the page doesn’t fully reload with every click. Now let’s see the React Router Link in action!  This short guide will give you a basic understanding of how to handle navigation in a React application. By the end of the tutorial, you should understand how Link , NavLink and Redirect work, so that you can create a functional multi-page application.  To make this easier to follow, we’ll create a small application that has three pages: The first two will use the Link and NavLink components, while the last one will make use of the Redirect component. Let’s get started! This article explains the React Router Link component, which is used in web applications for changing the client view and loading different pages based on route parameters.  To get the most out of this guide, you should be familiar with:  React Router is used for handling navigation state and keeping the UI in sync with the URL. It watches for changes in the browser URL and displays the UI components that match the route configuration.  Thus, in order to navigate between pages in a web application using the React Router, we need to:  Please notice how I’ve mentioned two different concepts: the router and the route. Both are React components, but they’re not rendered on the page, so they don’t add elements to the DOM by themselves.  Instead, what these two components do is to handle the logic and define the rules for the application’s functioning. The Router component “oversees” or coordinates all the components defined in the routes, while the Routes define the components that should be rendered for each route or path.  To understand this concept better, let’s look at how a single component is rendered in React, first without React Router in place. If we want to use the Router component to render the app, we first need to define the route or path where the App component will be rendered. This is usually the homepage of the app, so the route will be “/”, and the name of the page “Home”.  In this case, our code needs to be adjusted as follows:  Similarly, we can define the components that we want to render on the other pages of the app: The “About us” page will only be rendered when the path matches the URL, and if the user wants to navigate to the homepage again, this will happen without a request to the server.  We’ll explore this example further in the next sections, but first we should get an overview of all the components available in React Router for navigation purposes. The Link component that we saw above is used for internal links, but the navigation of a web app usually makes use of a different component: NavLink .  If a page is outdated and you want to direct users to a newer version or to a completely different page, you can make use of the Redirect  component.  So we have three basic options for handling path changes in React apps, if we go the React Router way:  For changing the route and displaying another component when the URL changes, we can use the <Route> component mentioned above. However, there’s one problem with this component: Route renders all its components .  This makes it useful when you want to display the main menu on all pages for example, but it becomes problematic if you have pages where you don’t want the menu to be displayed fully. For example, if you have a landing page where you want the user to fill in a form, or a checkout flow where you want to remove distractions, you don’t want to display the full navigation.  In such cases, you can use Switch instead of Route . The former component is similar to the latter, in the sense that it renders links, but it only displays the first link element whose path matches the current URL. Thus, as a general rule, if you have multiple routes but want to render only one at a time, you should use Switch . Here's how the component looks:  We've covered the essential theory, now let’s see all this in action in a practical application! As mentioned in the beginning, for this example we’ll build a simple React application with three pages. I’ll use codesandbox.io and you can find the final code here . Before we start, we need to install two dependencies:  If you’re using create-react-app, please go ahead and initiate a new application, then install the dependencies above.  I'll first create the files needed for the project: Let's populate the Home, About and Contact pages with very simple React components that display a simple heading. Add the following code to the Home.js file: Then, add this code to the About.js file: Finally, add this code to the Contact.js file: All these are simple React functional components, so nothing complicated until now. Let's render all of them in the App.js file: As you can see, we're importing the Router , Route and Link components and rendering them all inside the app. If we run this code now, the links look a bit crowded, so let's style them quickly: We need to import the StyledLink component now in the app, instead of the Link one: Now let's run the code. You should see this app in your browser: Notice that the route is /contact , yet we're seeing the Homepage heading too. This happens because Router can only display one child, so we can try to solve the issue by adding exact in the routes. Let's see if this works. Now we see, indeed, only the components that match the exact path for each URL: This solution works for simple menus, but the code gets crowded when we have multiple nested routes. So let's try to use Switch instead, since we know that it's better practice. Our code will now look like this: I've wrapped the navigation in a nav tag to see a bit better that we're now basically only using two main components inside the router: the nav with its children, and the switch with its children. Although we can use the StyledLink components that we've created for the main menu, it's better practice to use NavLink instead of Link . This component adds styling by default to the rendered element, so in styles.js , let's make this change: We're almost done, except that now we're using only NavLinks and no Link components. Let's add two links in the About page: one using React Link, and the other one using a simple <a> tag. If you run this code, you'll see that the first link doesn't do anything except for adding "https://google.com" to the path. The second link takes you to the actual search engine page. This happens because the Link component is used only for handling internal links. So in this example, let's replace Google 1 with the Contact page and run the code again. When you click Contact now, the URL changes and you see the Contact component rendered. In a bigger website it's common to have pages that are outdated and you want to retire. While you can delete them from your database, that's not good practice, because the URL still remains in your sitemap, and users can still access it if they did previously. So when they access the deleted page, via the URL, they'll see a 404 error. To prevent this, whenever you want to retire a page, you can use a Redirect component instead of a Link or NavLink . Let's redirect the contact page from our example: When you want to render something special for a certain URL, for example you want to reuse a Campaign page template whenever you run a new campaign, you can use a custom link component. To do so, you first have to define it, so let's create a CampaignLink component: Since we're using the useRouteMatch hook, we need to import it in our App.js file, along with Link . Here's our final code: What we're doing here is that whenever we have a campaign page, we display "*** " in front of the navigation link when the page is active. Thus, if the URL matches "/campaign", the link of the campaign page in the main menu receives three stars in front. Until now, we've made all the page headings static, but we can turn them into dynamic titles with the help of props. Let's do this for the Campaign page. First, we'll adjust the component rendered by Campaign.js : Now let's pass the title as prop in the App.js file: The page will render with this title. Let's assume that in this page we have hundreds of items, and we want to allow users to search only for a category, let's say Sunglasses. When the URL changes by receiving the query parameter ?q="sunglasses" , we should render the Sunglasses component. At the same time, when the user searches for Dresses, we want to show only the dresses, but we don't want the full URL to change. So we don't want the user to be redirected to /campaign/dresses , but to /campaign?q='dresses' First, we need to adjust the campaign page. We'll use the useLocation hook to match the URL to the query. We'll define a new Collection component that will render a div and will take the name of the collection as prop. To make use of the name variable, we'll use the .get() method of the URLSearchParams API . Now we need to create the two components for the collections: Dresses.js and Sunglasses.js. Let's populate both files with a simple heading component, as follows: If we run the code and navigate to Campaign, then click the Sunglasses collection, we should see that the query parameter is added to the URL, and the Sunglasses component is rendered: As you can see, React Router Link along with its variations NavLink and Redirect make it easy to work with internal links in a React app. While this isn't the only method to handle navigation, it's definitely the most popular one, as it simplifies your work a lot. If you want to learn more about React Router, you can find an awesome tutorial with a lot of practical examples here .

Thumbnail Image of Tutorial How to handle navigation in your app with React Router Link

Using react-portal to Show Modals and Alerts in React

In this article, we will learn how to use the react-portal for displaying modal messages in React applications. We will learn how to add and configure the component. We will also consider available alternative solutions and when you might want to use them.The idea of components hierarchy is essential to React. The parent component is a container where child components get rendered. This allows us to easily reason about the structure of React applications. By changing the position and visibility of a parent component, we affect all its children as well. However, this might cause complexities in some cases. A good example is when a child component should render apart from its parent, like a modal dialog, alert message, or a hovercard. Let's take a closer look at this problem before discussing the solution. For this article, we assume that you're familiar with React components basics, such as working with component's properties. Let's look at the case when the parent limits the rendering of its child components: We've got the MyModal component and we control its visibility with the isOpen state variable. Note how the message with the green border got clipped by its parent. It happens because the parent has got the overflow:hidden CSS style. We can fix this by modifying the CSS, but this will tie our parent and child components. It would be complex to re-use a child component in the future as this requires a specific CSS configuration to display it properly. There is a better way to do that in React. Let's look at how react-portal can help. This package provides an easy way to display modals in React. We start by adding the react-portal package to a project: The react-portal package provides the Portal component that we can use. Now, let's render a modal using the Portal component from the react-portal package: The only difference from the first example is that we import the Portal component from the react-portal package. Next, we wrap the content of the MyModal component with the Portal component. Now the MyModal component renders properly. If we'll take a look at the resulting markup, we will see that the MyModal component has been rendered directly to the document.body instead of the parent App component. This makes it easy to position the component as we please. The Portal component takes care of mounting a container to the document.body . This approach works with server-side rendering as well. Components declared inside the Portal component will be rendered outside the parent component. But we still can work with them as usual, handle events, and pass properties to them. The react-portal also provides the PortalWithState component which is an advanced version of the Portal component. It handles the closing of a component on hitting the ESC key or clicking outside of the component. You might check the PortalWithState documentation to learn more. The react-portal helps you to render modals but it does not control positioning or overlays for you. It is a great choice when you need maximum flexibility. If you're willing to trade some flexibility for additional features, here are several options for you. If you only need modal dialogs , the react-modal package provides a specialized component for displaying modal dialogs. If you just need to display tooltips , the react-tooltip package provides a component for displaying tooltips with lots of advanced features. If you're using one of the popular UI frameworks , feel free to use components provided by a framework. Popular UI frameworks such as Material UI , Bootstrap , and Semantic UI provide components for modals, alerts, and tooltips. There are many ways to render modals, alerts, and hovercards in React applications. The react-portal provides a small, flexible component that you can use when you need to move a component out of its parent. There are also alternative solutions available, such as react-modal , react-tooltip , and modal components from popular UI frameworks like Material UI, React Bootstrap, and Semantic UI.