Categories
React Answers

How to Get Path Params in React Router?

Sometimes, we want to get path params in React Router.

In this article, we’ll look at how to get path params in React Router.

Get Path Params in React Router

To get path params in React Router, we can use the useParams hook.

For instance, we write:

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

const Child = () => {
  const { id } = useParams();

  return (
    <div>
      <h3>ID: {id}</h3>
    </div>
  );
};

export default function App() {
  return (
    <Router>
      <div>
        <h2>Accounts</h2>

        <ul>
          <li>
            <Link to="/1">foo</Link>
          </li>
          <li>
            <Link to="/2">bar</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/:id/" children={<Child />} />
        </Switch>
      </div>
    </Router>
  );
}

We create the Child component that calls the useParams hook to return an object with the route params in the URL.

And we render the value of the id param on the page.

In App, we have 2 links that goes to routes with different id param values.

To render Child when we click on the link, we add the Route in the Switch component.

And we set the path to /:id/. and children to Children.

:id is the route param placeholder, so id will be returned in useParams.

Conclusion

To get path params in React Router, we can use the useParams hook.

Categories
React Answers

How to Draw a Red Horizontal Line in React?

Sometimes, we want to draw a red horizontal line in React.

In this article, we’ll look at how to draw a red horizontal line in React.

Draw a Red Horizontal Line in React

To draw a red horizontal line in React, we can add an hr element that has a height and background color.

For instance, we write:

import React from "react";

const ColoredLine = ({ color }) => (
  <hr
    style={{
      color,
      backgroundColor: color,
      height: 5
    }}
  />
);
export default function App() {
  return (
    <div>
      <ColoredLine color="red" />
    </div>
  );
}

We create the ColoredLine component that takes the color prop.

And we set the style prop to an object with the color, backgroundColor and the height properties.

backgroundColor makes the line set to color.

Now we should see the line displayed.

Conclusion

To draw a red horizontal line in React, we can add an hr element that has a height and background color.

Categories
React Answers

How to Add a Background Image in React Component?

Sometimes, we want to add a background image in React component.

In this article, we’ll look at how to add a background image in React component.

Add a Background Image in React Component

To add a background image in React component, we can set the backgroundImage property of the object we set as the value of the style prop.

For instance, we write:

import React from "react";

const styles = {
  height: 300,
  backgroundImage: `url(${"https://blog.prezi.com/wp-content/uploads/2019/03/water_ripple-1024x683.jpg"})`
};

export default function App() {
  return <div style={styles}></div>;
}

We have the styles object with the backgroundImage property set to a URL of the background image we want to show.

Then we set the styles prop to the styles object.

Now we see the background image displayed.

Conclusion

To add a background image in React component, we can set the backgroundImage property of the object we set as the value of the style prop.

Categories
React Answers

How to Add a Smooth Scrolling Back To Top Button with React?

Sometimes, we want how to add a smooth scrolling back to top button with React.

In this article, we’ll look at how to add a smooth scrolling back to top button with React.

Add a Smooth Scrolling Back To Top Button with React

To add a smooth scrolling back to top button with React, we can create our own function to scroll up the screen until we reach the top.

Then we can use that function as the click handler for the scroll to top button.

For instance, we write:

import React from "react";

export default function App() {
  const scrollUp = () => {
    const doc = document.documentElement;
    const top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);

    if (top > 0) {
      window.scrollTo(0, top - 15);
      setTimeout(scrollUp, 10);
    }
  };

  return (
    <div>
      {Array(200)
        .fill()
        .map((_, i) => (
          <p key={i}>{i}</p>
        ))}
      <button onClick={scrollUp}>scroll to top</button>
    </div>
  );
}

We have the scrollUp function that takes the document.documentElement element which is the element with the whole page’s contents.

Then we get the top position to scroll to with (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0).

And if top is bigger than 0, we call window.scrollTo to scroll higher up the page.

Then we call scrollUp after a timeout to keep scrolling until we reached the top.

Finally, we set scrollUp as the value of onClick so that we get smooth scrolling back to the top of the page when we click on the scroll to top button.

Conclusion

To add a smooth scrolling back to top button with React, we can create our own function to scroll up the screen until we reach the top.

Then we can use that function as the click handler for the scroll to top button.

Categories
React Answers

How to Focus on the Next Field When Pressing Enter in React?

Sometimes, we want to focus on the next field when pressing enter in React.

In this article, we’ll look at how to focus on the next field when pressing enter in React.

Focus on the Next Field When Pressing Enter in React

To focus on the next field when pressing enter in React, we can set the onKeyDown prop of the inputs to a function that gets the next input and call focus on it.

To do this, we write:

import React from "react";

export default function App() {
  const handleEnter = (event) => {
    if (event.key.toLowerCase() === "enter") {
      const form = event.target.form;
      const index = [...form].indexOf(event.target);
      form.elements[index + 1].focus();
      event.preventDefault();
    }
  };

  return (
    <form>
      <input onKeyDown={handleEnter} placeholder="field 1" />
      <input onKeyDown={handleEnter} placeholder="field 2" />
      <input placeholder="field 3" />
    </form>
  );
}

We have the handleEnter function that checks if the pressed key is Enter by checking the event.key property.

Then we get the form element that the input is in with the event.target.form property.

Next, we spread the form iterable object into an array and then call indexOf of it with event.target to get the index of the input we’re currently focused on.

And then we get the next input with form.elements[index + 1] to get the next input and call focus on it.

Finally, we call event.preventDefault to prevent the default browser behavior of pressing enter which we don’t want.

Now when we press enter, the focus will be switched to the next input.

Conclusion

To focus on the next field when pressing enter in React, we can set the onKeyDown prop of the inputs to a function that gets the next input and call focus on it.