Categories
React Answers

How to call child method from parent with React?

Sometimes, we want to call child method from parent with React.

In this article, we’ll look at how to call child method from parent with React.

How to call child method from parent with React?

To call child method from parent with React, we pass a ref to the child and assign the ref’s vale to the child’s function.

For instance, we write

const { forwardRef, useRef, useImperativeHandle } = React;

const Child = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    getAlert() {
      alert("getAlert from Child");
    },
  }));

  return <h1>Hi</h1>;
});

const Parent = () => {
  const childRef = useRef();

  return (
    <div>
      <Child ref={childRef} />
      <button onClick={() => childRef.current.getAlert()}>Click</button>
    </div>
  );
}

to create the Child component bwith the forwardRef function.

We call useImperativeHandle with the ref parameter so we can assign the function the 2nd argument to the ref.

Then in Parent, we create the ref with useRef and then pass it to the Child via the ref prop.

And then we can call childRef.current.getAlert in the onClick handler to show the alert.

Categories
React Answers

How to detect click outside React component?

Sometimes, we want to detect click outside React component.

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

How to detect click outside React component?

To detect click outside React component, we create our own hook.

For instance, we write

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

export default function useComponentVisible(initialIsVisible) {
  const [isComponentVisible, setIsComponentVisible] =
    useState(initialIsVisible);
  const ref = useRef(null);

  const handleClickOutside = (event) => {
    if (ref.current && !ref.current.contains(event.target)) {
      setIsComponentVisible(false);
    }
  };

  useEffect(() => {
    document.addEventListener("click", handleClickOutside, true);
    return () => {
      document.removeEventListener("click", handleClickOutside, true);
    };
  }, []);

  return { ref, isComponentVisible, setIsComponentVisible };
}

to define the useComponentVisible with the initialVisible parameter.

In it, we define the handleClickOutside that checks if we clicked outside with ref.current && !ref.current.contains(event.target).

If we did, then we set isComponentVisible to false.

And we use that as the click handler for document.

Then we use it by writing

const DropDown = () => {
  const { ref, isComponentVisible } = useComponentVisible(true);
  return <div ref={ref}>{isComponentVisible && <p>Dropdown Component</p>}</div>;
};

to get the ref returned by useComponentVisible.

If isComponentVisible is true, then we render the p element.

Conclusion

To detect click outside React component, we create our own hook.

Categories
React Answers

How to show or hide element in React?

Sometimes, we want to show or hide element in React.

In this article, we’ll look at how to show or hide element in React.

How to show or hide element in React?

To show or hide element in React, we can check a state before rendering a component.

For instance, we write

const Results = () => (
  <div id="results" className="search-results">
    Results
  </div>
);

const Search = () => {
  const [showResults, setShowResults] = React.useState(false);
  const onClick = () => setShowResults(true);
  return (
    <div>
      <input type="submit" value="Search" onClick={onClick} />
      {showResults ? <Results /> : null}
    </div>
  );
};

to define Search component.

In it, we have the showResulrs state.

We set showResults in the onClick function with setShowResults(true);.

Then we set onClick as the value of the onClick prop to make showResults true when we click the button.

And then Results will show when showResults is true.

Conclusion

To show or hide element in React, we can check a state before rendering a component.

Categories
React Answers

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

Sometimes, we want to fix ‘A component is changing an uncontrolled input of type text to be controlled’ error in React.

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

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

To fix ‘A component is changing an uncontrolled input of type text to be controlled’ error in React, we should make sure the value prop is always set to something other than null or undefined.

For instance, we write

<input
  id={myId}
  name={myName}
  type="checkbox"
  value={myStateValue ?? ""}
  checked={someBoolean ? someBoolean : false}
/>;

to set the value prop to myStateValue ?? "".

If myStateValue is null or undefined, then value is set to an empty string.

Then the input always stays a controlled input.

Conclusion

To fix ‘A component is changing an uncontrolled input of type text to be controlled’ error in React, we should make sure the value prop is always set to something other than null or undefined.

Categories
React Answers

How to fix ‘Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object ‘ with React?

Sometimes, we want to fix ‘Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object ‘ with React.

In this article, we’ll look at how to fix ‘Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object ‘ with React.

How to fix ‘Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object ‘ with React?

To fix ‘Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object ‘ with React, we should make sure we don’t confuse named and default imports.

For instance, we write

import { MyComponent } from "../components/xyz.js";

to import the MyComponent as a named import.

The name matters in a named import.

If MyComponent is a default export, then we write

import MyComponent from "../components/xyz.js";

to import it.

Conclusion

To fix ‘Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function but got: object ‘ with React, we should make sure we don’t confuse named and default imports.