Categories
React Answers

How to Conditionally Apply Class Attributes with React?

Sonmetimes, we want to conditionally apply class attributes with React.

In this article, we’ll look at how to conditionally apply class attributes with React.

Conditionally Apply Class Attributes with React

To conditionally apply class attributes with React, we can use the classnames library.

We install it by running:

npm i classnames

Then we write:

import classNames from "classnames";
import React from "react";

const btnGroupClasses = classNames("btn-group", "pull-right", {
  show: true,
  hidden: false
});

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

We call classNames with the class name strings we want to add.

And we pass in an object with show set to true and hidden set to false to add the showclass and omit thehidden` class.

We assign the returned class name string to btnGroupClasses.

And then we set className to btnGroupClasses to add the classes.

Therefore, the div should have btn-group, pull-right, and show classes added.

Conclusion

To conditionally apply class attributes with React, we can use the classnames library.

Categories
React Answers

How to Add Multiple Classes to a React Component?

Sometimes, we want to add multiple classes to a React component.

In this article, we’ll look at how to add multiple classes to a React component.

Add Multiple Classes to a React Component

To add multiple classes to a React component, we can pass in an array of class name strings and join them together with a space.

For instance, we write:

import React from "react";

const isEnabled = true;
const isChecked = false;

export default function App() {
  return (
    <div
      className={[isEnabled && "enabled", isChecked && "checked"]
        .filter((e) => !!e)
        .join(" ")}
    >
      hello world
    </div>
  );
}

We set the isEnabled to true and isChecked to false.

Then we set the className attribute to an array with isEnabled && "enabled" and isChecked && "checked" so that the strings are only added when the operand before the && is truthy.

Then we call filter with a callback to filter out the falsy values.

Finally, we call join with a space to join the class names together.

Therefore, the div should render with the enabled class only.

Conclusion

To add multiple classes to a React component, we can pass in an array of class name strings and join them together with a space.

Categories
React Answers

How to Detect Clicks Outside a React Component?

Sometimes, we want to detect clicks outside a React component.

In this article, we’ll look at how to detect clicks outside a React component.

Detect Clicks Outside a React Component

To detect clicks outside a React component, we can create our own hook that detects whether we clicked outside the component with the DOM node’s contains method.

For instance, we can write:

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

const useOutsideAlerter = (ref) => {
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (!ref.current?.contains(event.target)) {
        console.log("clicked outside");
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [ref]);
};

export default function App() {
  const wrapperRef = useRef(null);
  useOutsideAlerter(wrapperRef);

  return <div ref={wrapperRef}>hello world</div>;
}

We create the useOutsideAlerter hook that takes a ref parameter.

Then we call the useEffect hook with an array with the ref as the 2nd argument to watch it for changes.

In the useEffect callback, we define the handleClickOutside function that checks if we clicked outside the component assigned to the ref with:

!ref.current?.contains(event.target)

event.target is the element we clicked on.

Therefore, if that is false, we clicked outside the component assigned to the ref and we log 'clicked outside'.

Next, we call document.addEventListener with 'mousedown' to listen to the mousedown event.

And we use handleClickOutside as the mousedown event listener.

Then we return a function that calls document.removeListener with 'mousedown' and handleClickOutside to remove the event listener when the component unmounts.

In App, we assign a ref to the div and we called the useOutsideAlerter hook with the ref.

So when we click outside the div, we see 'clicked outside' logged.

Conclusion

To detect clicks outside a React component, we can create our own hook that detects whether we clicked outside the component with the DOM node’s contains method.

Categories
React Answers

How to Fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React?

Sometimes, we may run into the ‘A component is changing an uncontrolled input of type text to be controlled’ error when we’re developing React apps.

In this article, we’ll look at how to fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React.

Fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React

To fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React, we should make sure the value prop of the input is always set to a string.

For instance, we can write:

import React, { useState } from "react";

export default function App() {
  const [value, setValue] = useState();

  return (
    <div>
      <input
        name="name"
        value={value ?? ""}
        onChange={(e) => setValue(e.target.value)}
      />
    </div>
  );
}

to create the value state with the useState hook.

Its initial value is undefined.

Then in the input, we set the value prop to value ?? "" so that the value prop is set to an empty string when the value state is undefined or null.

Now we shouldn’t see this error in the console anymore.

Conclusion

To fix the ‘A component is changing an uncontrolled input of type text to be controlled’ error in React, we should make sure the value prop of the input is always set to a string.

Categories
React Answers

How to Set Focus on an Input Field After Rendering with React?

Sometimes, we want to set focus on an input field after rendering with React.

In this article, we’ll look at how to set focus on an input field after rendering with React.

Set Focus on an Input Field After Rendering with React

To set focus on an input field after rendering with React, we can assign a ref to the input element with the useRef hook.

Then we call focus on the current value of the ref to focus on the input.

For instance, we write:

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

export default function App() {
  const inputReference = useRef(null);

  useEffect(() => {
    inputReference.current.focus();
  }, []);

  return (
    <div>
      <input ref={inputReference} />
    </div>
  );
}

to call useRef to create a ref and assign it to inputReference.

Then we call inputReference.current.focus() in the useEffect callback to focus on the input.

inputReference.current will be set to the input element when we set inputReference as the value of the ref prop of the input.

We pass in an empty array as the 2nd argument so that the useEffect callback only runs when the component mounts.

Finally, we assign the inputReference ref to the input by setting it as the value of the ref prop.

Conclusion

To set focus on an input field after rendering with React, we can assign a ref to the input element with the useRef hook.

Then we call focus on the current value of the ref to focus on the input.