Categories
React Answers

How to Use the Clsx Library to Set Class Names Dynamically in React?

Sometimes, we want to use the clsx Library to set class names dynamically in React.

In this article, we’ll look at how to use the clsx Library to set class names dynamically in React.

Use the Clsx Library to Set Class Names Dynamically in React

To use the clsx Library to set class names dynamically in React, we call the clsx function with an object that has the class names as the property names.

And the values of the properties would be the condition of which the class names will be applied.

For instance, we can write:

import clsx from "clsx";
import React from "react";

const menuStyle = clsx({
  root: true,
  menuOpen: false
});

export default function App() {
  return <div className={menuStyle}></div>;
}

We call clsx with:

{
  root: true,
  menuOpen: false
}

to add the root class and skip the menuOpen class.

We pass the returned string as the value of the className prop to set the class names.

Conclusion

To use the clsx Library to set class names dynamically in React, we call the clsx function with an object that has the class names as the property names.

And the values of the properties would be the condition of which the class names will be applied.

Categories
React Answers

How to Update Meta Tags in React?

Sometimes, we want to update meta tags in React.

In this article, we’ll look at how to update meta tags in React.

Update Meta Tags in React

To update meta tags in React, we can use the react-document-meta library.

To install it, we run:

npm i react-document-meta

Then we can change the meta tags by writing:

import React from "react";
import DocumentMeta from "react-document-meta";

const meta = {
  title: "Some Meta Title",
  description: "I am a description, and I can create multiple tags",
  canonical: "http://example.com/path/to/page",
  meta: {
    charset: "utf-8",
    name: {
      keywords: "react,meta,document,html,tags"
    }
  }
};

export default function App() {
  return (
    <div>
      <DocumentMeta {...meta} />
    </div>
  );
}

We set the title meta tag with the title property.

We set the description meta tag with the description property.

We set the canonical meta tag with the canonical property.

And we set the other meta tags with the meta property.

We spread the meta object as the props for the DocumentMeta component to set the meta tags.

Conclusion

To update meta tags in React, we can use the react-document-meta library.

Categories
React Answers

How to Cancel or Abort Ajax Requests in Axios in a React App?

Sometimes, we want to cancel or abort ajax requests in Axios in a React app.

In this article, we’ll look at how to cancel or abort ajax requests in Axios in a React app.

Cancel or Abort Ajax Requests in Axios in a React App

To cancel or abort ajax requests in Axios in a React app, we can use the Axios cancel token feature.

For instance, we can write:

import React, { useRef, useState } from "react";
import axios from "axios";

export default function App() {
  const [answer, setAnswer] = useState({});
  const cancelTokenSource = useRef();

  const request = async () => {
    try {
      setAnswer({});
      cancelTokenSource.current = axios.CancelToken.source();
      const { data } = await axios.get("https://yesno.wtf/api", {
        cancelToken: cancelTokenSource.current.token
      });
      setAnswer(data);
    } catch (error) {
      console.log(error);
    }
  };

  const cancel = () => {
    cancelTokenSource.current.cancel();
  };

  return (
    <div>
      <button onClick={request}>request</button>
      <button onClick={cancel}>cancel</button>
      <div>{JSON.stringify(answer)}</div>
    </div>
  );
}

We define the answer state to store the request response.

And we have the cancelTokenSource ref to store the cancellation token.

In the request function, we set the cancelTokenSource.current to the axios.CancelToken.source() which returns the cancel token object.

And then when we make the request with axios.get , we set cancelToken to the cancel token.

Next, we get the data and set it to answer .

Then we define the cancel function that calls the cancel method that comes with the cancel token to cancel the request.

Conclusion

To cancel or abort ajax requests in Axios in a React app, we can use the Axios cancel token feature.

Categories
React Answers

How to Check if the React Component is Unmounted?

Sometimes, we want to check if the React component is unmounted.

In this article, we’ll look at how to check if the React component is unmounted.

Check if the React Component is Unmounted

To check if the React component is unmounted, we can set a state in the callback that’s returned in the useEffect hook callback.

For instance, we can write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [isMounted, setIsMounted] = useState(false);

  useEffect(() => {
    setIsMounted(true);
    return () => setIsMounted(false);
  }, []);
  return <div>{isMounted.toString()}</div>;
}

We create the isMounted state with the useState hook.

Then we call the useEffect hook with a callback that calls setIsMounted to set isMounted to true .

And since the function that’s returned in the useEffect callback runs when the component unmounts, we can call setIsMounted to set isMounted to false there.

Finally, we render the value of isMounted is the div.

Conclusion

To check if the React component is unmounted, we can set a state in the callback that’s returned in the useEffect hook callback.

Categories
JavaScript

Template Strings in JavaScript

Template strings are a powerful feature of modern JavaScript released in ES6. It lets us insert/interpolate variables and expressions into strings without needing to concatenate like in older versions of JavaScript. It allows us to create strings that are complex and contain dynamic elements. Another great thing that comes with template strings are tags. Tags are functions that take a string and the decomposed parts of the string as parameters and are great for converting strings to different entities.

The syntax for creating template strings is by using backticks to delimit them. For example, we can write:

`This is a string`

This is a very simple example of a template string. All the content is constant and there are no variables or expressions in it. To add variables and or expressions to a string, we can do the following.

Interpolating Variables and Expressions

// New JS with templates and interpolation
const oldEnoughToDrink = age >= 21;
const oldEnough = `You are ${oldEnoughToDrink ? 'old enough' : 'too young'} to drink.`

We insert a variable or expression by adding a dollar sign $ and curly braces {} into the string ${variable}. This is much better than the alternative in old JavaScript where we had to concatenate a string like the following:

// Old JS using concatenation
const oldEnoughToDrink = age >= 21;
const oldEnough = 'You are ' + (oldEnoughToDrink ? 'old enough' : 'too young') + ' to drink.'

As we can see it’s easy to make syntax errors with the old concatenation syntax if we have complex variables and expressions. Therefore template strings are a great improvement from what we had before.

If we want to use the backtick character in the content of string just put a \ before the backtick character in the string will have a literal back tick.

Multiline Strings

Another great feature of template strings is that we can have strings with multiple lines for better code readability. This cannot be done in an easy way with the old style of strings. With the old style of strings, we had to concatenate each line of the string to put long strings in multiple lines like the following examples:

const multilineStr = 'This is a very long string' +
  'that spans multiple lines.'

const multllineStr2 = 'At vero eos et accusamus et iusto odio' + 'dignissimos ducimus qui blanditiis praesentium voluptatum ' + 'deleniti atque corrupti quos dolores et quas molestias ' + 'excepturi sint occaecati cupiditate non provident, ' +
'similique sunt in culpa qui ' +
'officia deserunt mollitia animi.'

As we can see, this will become really painful is we have many more lines. It’s very frustrating to have all those plus signs and divide the string into multiple lines.

With template strings, we don’t have this problem:

const longString = `At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi.`

This is much better than concatenating strings together. It takes a lot less time to write the code and a lower probability of syntax errors. It’s also much more readable.

Note that this method does add an actual new like to the string \n and if you don’t want the string to have multiple lines in its final format, just put a \ at the end of the line.

Nesting Templates

Template strings can be nested in each other. This is a great feature because many people want to create dynamic strings. Template strings allow us to nest regular strings or template strings within template strings. For example, we can write the following:

const oldEnoughToDrink = age >= 21;
const oldEnough = `You are ${oldEnoughToDrink ? 'old enough' : 'too young'} to drink.`

We can write the same thing with the expression interpolated in the string with template strings instead:

const TOO_YOUNG = 'too young';
const OLD_ENOUGH = 'old enough';

const oldEnoughToDrink = age >= 21;

const oldEnough = `You are ${oldEnoughToDrink ? OLD_ENOUGH : TOO_YOUNG} to drink.`

This case is simple, but with complex string combinations, it is very powerful to be able to add logic to how we build our strings.

Tagged Templates

With template strings, we can add something called tags in front of a template string. They are functions that take a string and the decomposed parts of the string as parameters. A tagged function decomposes the template string into an array as the first parameter, with each item of the array as the constant parts of the string. The additional parameters of the function are all the variables and expressions in the order in which they appear in the string.

const personOldTag = (strings, nameExp, ageExp, genderExp)=>{
  let str0 = strings[0];

  let oldStr;
  if (ageExp > 75){
    oldStr = 'senior';
  } else {
    oldStr = 'young';
  }

  // We can even return a string built using a template literal
  return `${nameExp}${str0}${oldStr}${genderExp}.`;
}

const name = 'Bob'
const age = 80;
const gender = 'male;

const result = personOldTag`` `${ name } is a ${ age } year old ${ gender }`;``

// result should be `Bob is a `senior` man.`

Tagged templates are great for converting strings to anything you want since it’s just a regular function. However, it is a special function because the first parameter is an array containing the constant parts of the string. The rest of the parameters contain the returned values that each expression returns. This is great for manipulating the string and transforming the returned values to what we want.

The return value of tags can be anything you want. So we can return strings, arrays, objects, or anything else.

As we see in the function above, in the string that we put beside the personOldTag, we first interpolated the name, then the age , then the gender. So in the parameters, they also appear in this order — nameExp, ageEx, and genderExp. They are the evaluated versions of the name, age, and gender in the template string.

Since tags are functions, we can return anything we want:

const isOldTag = (strings, nameExp, ageExp, genderExp)=>{
  let str0 = strings[0];
  return ageExp > 75
}

const name = 'Bob'
const age = 80;
const gender = 'male;

const result = isOldTag`${ name } is a ${ age } year old ${ gender }`;

// result is true

As you can see, we can manipulate the data to return a boolean instead of a string. Template tags are a feature that’s only available for template strings. To do the same thing with the old style of strings, we have to decompose the strings with our own string manipulating code and the built-in string manipulation functions, which is nowhere near as flexible as using tags. It decomposes the parts of a string into arguments for you that get passed in the template tags.

Raw Strings

Template strings have a special raw property that you can get from tags. The raw property gets us the string without escaping the special characters, hence the property is called raw. To access the raw property of a string, we can follow the example:

const logTag = (strings) => {
  console.log(strings.raw[0]);
}

logTag`line 1 \r\n line 2`;
// logs "line 1 \r\n line 2" including characters '\', 'r' and 'n'

This is handy for visualizing the string as-is with the special characters intact.

There’s also the String.raw tag where we can take a template string and return a string with the escape characters without actually escaping them to see the string in its full form. For example, with the String.raw tag, we can write:

let hello = String.raw`Hello\n${'world'}!`;
// "Hi\nworld!"

hello.length;
// 13

hello.split('').join(',');
// "`H,e,l,l,o,\\,n,w,o,r,l,d,!`"

As we can see, we have all the characters of the string with the expressions evaluated, but we keep the escape characters as is.

Support for Template Strings

Template strings are supported by almost all browsers that are regularly maintained today. The only major one that doesn’t support it right out of the box is Internet Explorer. However, browsers that do not support it can add it with Babel. Node.js also supports it in version 4 or later.

Template strings are the new standard for JavaScript strings. It is much better than strings before ES6 in that it supports interpolating expressions inside strings. We also have tagged templates which are just functions, with the decomposed parts of the template string as parameters. The constant string in the first parameter is the string in a decomposed array form, and the evaluated versions of the expressions in the order they appeared in the string are the remaining arguments. Tagged template functions can return any variable type.

With the raw property of a string, which is available in tags, can get the string with the escape characters unescaped.