Categories
React Answers

What is the Equivalent of document.getElementById() in React?

The equivalent of document.getElementById in React is refs.

We can assign a ref to an element and then retrieve the element that’s assigned the ref from the ref’s current property.

For instance, we write:

import React, { useRef } from "react";

export default function App() {
  const myContainer = useRef(null);
  console.log(myContainer.current);

  return (
    <>
      <div ref={myContainer}>I can use the DOM with react ref</div>
    </>
  );
}

to create a ref with the useRef hook and assign it to myContainer.

Then we assign the ref to the div by setting the ref prop of the div to myContainer.

Finally, we get the div by using the myContainer.current property.

Therefore, the console log should log the div as the value.

Categories
React Answers

How to Map Multiple Path Names to the Same Component in React Router v5?

Sometimes, we want to map multiple path names to the same component in React Router v5.

In this article, we’ll look at how to map multiple path names to the same component in React Router v5.

Map Multiple Path Names to the Same Component in React Router v5

To map multiple path names to the same component in React Router v5, we can add a | symbol between the paths that we want to match.

For instance, we write:

import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

const Child = () => {
  return (
    <div>
      <p>foo</p>
    </div>
  );
};

export default function App() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/foo">foo</Link>
          </li>
          <li>
            <Link to="/bar">bar</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/(foo|bar)/" children={<Child />} />
        </Switch>
      </div>
    </Router>
  );
}

We create the Child component which we map either to the foo path or the bar path with '/(foo|bar)/'.

children is set to Child so it’ll be rendered.

And we have one Link that goes to the foo path and another that goes to bar.

Therefore, when we click on either link, we see ‘foo’ displayed.

Conclusion

To map multiple path names to the same component in React Router v5, we can add a | symbol between the paths that we want to match.

Categories
React Answers

How to Get the Height of an Element with React?

Sometimes, we want to get the height of an element with React.

In this article, we’ll look at how to get the height of an element with React.

Get the Height of an Element with React

To get the height of an element with React, we can assign a ref to the element we want to get the height for.

Then we can use the clientHeight property to get the height.

For instance, we write:

import React, { useRef } from "react";

export default function App() {
  const elementRef = useRef(null);
  console.log(elementRef.current?.clientHeight);

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

We call the useRef hook and assign the returned ref to elementRef.

Then we set elementRef as the value of the ref prop of the div.

Finally, we log the height of the div by logging elementRef.current?.clientHeight.

Therefore, we should see 18 logged, which is the height of the div in pixels.

Conclusion

To get the height of an element with React, we can assign a ref to the element we want to get the height for.

Then we can use the clientHeight property to get the height.

Categories
React Answers

How to Detect Esc Key Press in React?

Sometimes, we want to detect Esc Key Press in React.

In this article, we’ll look at how to detect Esc Key Press in React.

Detect Esc Key Press in React

To detect Esc Key Press in React, we can add an event listener for the keydown event.

For instance, we write:

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

export default function App() {
  const escFunction = useCallback((event) => {
    if (event.keyCode === 27) {
      console.log("esc pressed");
    }
  }, []);

  useEffect(() => {
    document.addEventListener("keydown", escFunction);

    return () => {
      document.removeEventListener("keydown", escFunction);
    };
  }, [escFunction]);

  return <div>hello</div>;
}

to define the escFunction function.

We check if event.keyCode is 27.

If it is, then the Esc key is pressed.

Then in the useEffect callback, we call document.addEventListener with 'keydown' and escFunction to use escFunction as the keydown event handler.

This will add the listener for the whole page.

And we return the function that calls document.removeEventListener with the same arguments to remove the event listener when the component is unmounted.

Therefore, when we press the Esc key, we see 'esc pressed' in the console log.

Conclusion

To detect Esc Key Press in React, we can add an event listener for the keydown event.

Categories
React Answers

How to Go Back to the Previous Page with React Router v5?

To go back to the previous page with React Router v5, we can use the useHistory hook.

For instance, we write:

import React from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useHistory
} from "react-router-dom";

const Foo = () => {
  const history = useHistory();

  return (
    <div>
      <button onClick={history.goBack}>Back</button>
      <p>foo</p>
    </div>
  );
};

const Bar = () => {
  const history = useHistory();

  return (
    <div>
      <button onClick={history.goBack}>Back</button>
      <p>bar</p>
    </div>
  );
};

export default function App() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/foo">foo</Link>
          </li>
          <li>
            <Link to="/bar">bar</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/foo" children={<Foo />} />
          <Route path="/bar" children={<Bar />} />
        </Switch>
      </div>
    </Router>
  );
}

We have the Foo and Bar components which calls the useHistory hook.

In both components, we set the history.goBack method as the value of the onClick prop.

history.goBack lets us go back to the previous page.

In App, we have 2 Links that’s set to go to /foo and /bar respectively.

And we have 2 Routes that’s set to render Foo and Bar when we go to /foo and /bar respectively.

Therefore, when we click on the links and we click Back, we go to the previous page.