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 Reatct.

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

How to set focus on an input field after rendering with Reatct?

To set focus on an input field after rendering with React, we assign a ref to the input and then call focus on the ref’s value.

For instance, we write

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

const MyForm = () => {
  const textInput = useRef(null);

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

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

to define the MyForm component.

In it, we call useRef to create the textInput ref.

And then we assign that as the value of the ref prop of the input.

Then we call textInput.current.focus(); in the useEffect hook callback to focus on the input.

The callback is called when the component is mounted since the 2nd argument is an empty array.

Conclusion

To set focus on an input field after rendering with React, we assign a ref to the input and then call focus on the ref’s value.

Categories
React Answers

How to fix onClick can’t pass value to method with React?

Sometimes, we want to fix onClick can’t pass value to method with React.

In this article, we’ll look at how to fix onClick can’t pass value to method with React.

How to fix onClick can’t pass value to method with React?

To fix onClick can’t pass value to method with React, we set the onClick prop to a function that calls a function that takes the value we want.

For instance, we write

<th value={column} onClick={() => handleSort(column)}>
  {column}
</th>

to set the onClick prop to a function that calls handleSort with the column variable.

The function is called when we click on the th element.

Conclusion

To fix onClick can’t pass value to method with React, we set the onClick prop to a function that calls a function that takes the value we want.

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.