Categories
React Answers

How to register event with React useEffect hooks?

Sometimes, we want to register event with React useEffect hooks.

In this article, we’ll look at how to register event with React useEffect hooks.

How to register event with React useEffect hooks

To register event with React useEffect hooks, we can call the window.addEventListener method in the useEffect callback.

For instance, we write

//...

const Comp = () => {
  const [userText, setUserText] = useState("");
  const handleUserKeyPress = useCallback((event) => {
    const { key, keyCode } = event;
    if (keyCode === 32 || (keyCode >= 65 && keyCode <= 90)) {
      setUserText((prevUserText) => `${prevUserText}${key}`);
    }
  }, []);

  useEffect(() => {
    window.addEventListener("keydown", handleUserKeyPress);
    return () => {
      window.removeEventListener("keydown", handleUserKeyPress);
    };
  }, [handleUserKeyPress]);

  return (
    <div>
      <blockquote>{userText}</blockquote>
    </div>
  );
};

to create the userText state with the useState hook.

Then we creatr the handleUserKeyPress function that checks for the key that’s pressed.

And we call setUserText to append the key pressed to userText.

Then we call useEffect with a callback that calls window.addEventListener to listen to the keydown event.

And handleUserKeyPress is called when the keydown event is triggered.

The useEffect callback is run when handleUserKeyPress changes.

We return a function that calls window.removeEventListener to remove the keydown listener when handleUserKeyPress changes.

Conclusion

To register event with React useEffect hooks, we can call the window.addEventListener method in the useEffect callback.

Categories
React Answers

How to fix ‘Redirect’ is not exported from ‘react-router-dom’ with React Router v6?

Sometimes, we want to fix ‘Redirect’ is not exported from ‘react-router-dom’ with React Router v6.

In this article, we’ll look at how to fix ‘Redirect’ is not exported from ‘react-router-dom’ with React Router v6.

How to fix ‘Redirect’ is not exported from ‘react-router-dom’ with React Router v6?

To fix ‘Redirect’ is not exported from ‘react-router-dom’ with React Router v6, we should import Navigate instead of Redirect.

For instance, we write

import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate,
} from "react-router-dom";
import Home from "../home/Home";

export default function App() {
  return (
    <Router>
      <Routes>
        <Route path="/home" element={<Home />} />
        <Route path="/" element={<Navigate replace to="/home" />} />
      </Routes>
    </Router>
  );
}

to use the Navigate component to redirect to the /home route when we go to / as specified by

<Route path="/" element={<Navigate replace to="/home" />} />

Conclusion

To fix ‘Redirect’ is not exported from ‘react-router-dom’ with React Router v6, we should import Navigate instead of Redirect.

Categories
React Answers

How to correctly catch change or focusOut event on text input in React?

Sometimes, we want to correctly catch change or focusOut event on text input in React.

In this article, we’ll look at how to correctly catch change or focusOut event on text input in React.

How to correctly catch change or focusOut event on text input in React?

To correctly catch change or focusOut event on text input in React, we can watch the blur event.

For instance, we write

function Example() {
  return (
    <input
      onBlur={(e) => {
        console.log("Triggered because this input lost focus");
      }}
      placeholder="onBlur"
    />
  );
}

to add an input into the Example component.

We set its onBlur prop to a function that’s called when we move our focus away from the input.

Conclusion

To correctly catch change or focusOut event on text input in React, we can watch the blur event.

Categories
React Answers

How to go back to the previous route with React Route v4?

To go back to the previous route with React Route v4, we can use the history.goBack method.

For instance, we write

//...
import { withRouter } from "react-router-dom";

class Demo extends Component {
  //...
  constructor(props) {
    super(props);
    this.goBack = this.goBack.bind(this);
  }

  goBack() {
    this.props.history.goBack();
  }
  //...
}

export default withRouter(Demo);

to call the this.props.history.goBack method in goBack.

We get the method because we call withRouter with Demo to inject the history prop into the Demo component.

We call this.props.history.goBack method to go back to the previous route.

Categories
React Answers

How to select all text in input with React when it focused?

Sometimes, we want to select all text in input with React when it focused.

In this article, we’ll look at how to select all text in input with React when it focused.

How to select all text in input with React when it focused?

To select all text in input with React when it focused, we can call select on the input element to select the input value when the element is in focus.

For instance, we write

const Comp = () => {
  //...
  const inputEl = useRef(null);

  const handleFocus = () => {
    inputEl.current.select();
  };

  <input
    type="number"
    value={quantity}
    ref={inputEl}
    onChange={(e) => setQuantityHandler(e.target.value)}
    onFocus={handleFocus}
  />;
};

to assign the inputEl ref to the input.

Then we set the onFocus prop to the handleFocus function, which runs when we focus on the input.

In handleFocus, we call inputEl.current.select to select all the input value text in the input box.

Conclusion

To select all text in input with React when it focused, we can call select on the input element to select the input value when the element is in focus.