Categories
React Answers

How to Wrap One Component into Another with React?

Sometimes, we want to wrap one component into another with React.

In this article, we’ll look at how to wrap one component into another with React.

Wrap One Component into Another with React

To wrap one component into another with React, we add the children prop into the parent component.

For instance, we write:

import React from "react";

const Wrapper = ({ children }) => (
  <div>
    <div>header</div>
    <div>{children}</div>
    <div>footer</div>
  </div>
);

const Child = ({ name }) => <div>Hello {name}</div>;

export default function App() {
  return (
    <Wrapper>
      <Child name="foo" />
    </Wrapper>
  );
}

We create the Wrapper component that accepts the children prop.

And we put children in a div.

Next, we create the Child component that takes the name prop and renders some text.

In App, we wrap Wrapper around Child so that Child is set as a value in the children array.

Therefore, we see:

header
Hello foo
footer

rendered.

Conclusion

To wrap one component into another with React, we add the children prop into the parent component.

Categories
React Answers

How to scroll to top on every transition with React Router v5?

Sometimes, we want to scroll to top on every transition with React Router v5.

In this article, we’ll look at how to scroll to top on every transition with React Router v5.

Scroll to Top on Every Transition with React Router v5

To scroll to top on every transition with React Router v5, we can create a component that scrolls to the top every time we change routes and wrap that around the route components.

For instance, we can write:

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

const ScrollToTop = ({ history, children }) => {
  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    };
  }, [history]);

  return <>{children}</>;
};

const ScrollToTopWithRouter = withRouter(ScrollToTop);

const Foo = () => {
  return (
    <div>
      {Array(100)
        .fill()
        .map((_, i) => (
          <p key={i}>{i}</p>
        ))}
    </div>
  );
};

const Bar = () => {
  return (
    <div>
      {Array(100)
        .fill()
        .map((_, i) => (
          <p key={i}>{i}</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>
        <ScrollToTopWithRouter>
          <Switch>
            <Route path="/foo" children={<Foo />} />
            <Route path="/bar" children={<Bar />} />
          </Switch>
        </ScrollToTopWithRouter>
      </div>
    </Router>
  );
}

We create the Foo and Bar components which we use as the route components.

Then we create the ScrollToTop component that listens for route changes with the history.listen method in the useEffect callback.

In the history.listen callback, we call window.scrollTo(0, 0) to scroll to the top when the route changes.

And we call the unlisten method in the function we return in the useEffect callback when the component unmounts.

We render the children components, which contains the route components.

Next, we call the withRouter function with ScrollToTop to return a component that we can wrap around the route components to listen for route changes.

Then in App, we add the Links and the Routes so that when we click the Links the components set as the values of Route‘s children prop would be rendered.

Therefore, each time we click on the links, we should see that the page is scrolled to the top.

Conclusion

To scroll to top on every transition with React Router v5, we can create a component that scrolls to the top every time we change routes and wrap that around the route components.

Categories
React Answers

How to Add Optional Path Parameter with React Router v5?

Sometimes, we want to add optional path parameter with React Router v5.

In this article, we’ll look at how to add optional path parameter with React Router v5.

Add Optional Path Parameter with React Router v5

To add optional path parameter with React Router v5, we can add a ? after the route parameter placeholder.

For instance, we write:

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

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

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

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

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

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

We have the Route component that has the path prop set to '/:id/:slug?'.

And we make the slug parameter optional by adding the ? after it.

Also, we added links with the path set to a path with and without the second parameter respectively.

In the Child component, we use the useParams hook to get the value of both route parameters.

When we click in the foo link, we see that both id and slug have values.

And when we click on the bar link, we see only id is set.

We set the children prop to the Child component so that it’s rendered when we click on the links.

Conclusion

To add optional path parameter with React Router v5, we can add a ? after the route parameter placeholder.

Categories
React Answers

How to Listen to the Drop Down’s Change Event in React?

Sometimes, we want to listen to the drop down’s change event in React.

In this article, we’ll look at how to listen to the drop down’s change event in React.

Listen to the Drop Down’s Change Event in React

To listen to the drop down’s change event in React, we can set the onChange prop of the select element to the change event listener function.

For instance, we write:

import React, { useState } from "react";

const Dropdown = ({ options }) => {
  const [selectedOption, setSelectedOption] = useState(options[0].value);
  return (
    <select
      value={selectedOption}
      onChange={(e) => setSelectedOption(e.target.value)}
    >
      {options.map((o) => (
        <option key={o.value} value={o.value}>
          {o.label}
        </option>
      ))}
    </select>
  );
};

const options = [
  { value: "apple", label: "Apple" },
  { value: "orange", label: "Orange" },
  { value: "pear", label: "Pear" }
];

export default function App() {
  return <Dropdown options={options} />;
}

to define the Dropdown component that takes an array of options.

In the component, we define the selectedOption state, which is set to options[0].value initially, which is the value of the first option.

Then we set selectedOption as the value prop’s value.

And we set onChange to a function that calls setSelectedOption with e.target.value to set selectedOption to the value attribute’s value of the selected option.

In the select element, we render the option elements from the options array.

Finally, in App, we add the Dropdown component and set options to an options array.

Conclusion

To listen to the drop down’s change event in React, we can set the onChange prop of the select element to the change event listener function.

Categories
React Answers

How to Access Custom Attributes from an Event Object in React?

Sometimes, we want to access custom attributes from an event object in React.

In this article, we’ll look at how to access custom attributes from an event object in React.

Access Custom Attributes from an Event Object in React

To access custom attributes from an event object in React, we can use the e.currentTarget.dataset property.

For instance, we write:

import React from "react";

export default function App() {
  const onClick = (e) => {
    const tag = e.currentTarget.dataset.tag;
    console.log(tag);
  };

  return (
    <button data-tag="Tag Value" onClick={onClick}>
      Click me
    </button>
  );
}

We have the e.currentTarget.dataset.tag property to access the value of the data-tag attribute of the element we clicked on in the onClick function.

Then we assign the onClick function as the value of the onClick prop of the button.

And we set the data-tag attribute to Tag Value.

Now when we click on the button, we should see the data-tag attribute value logged in the console.

Conclusion

To access custom attributes from an event object in React, we can use the e.currentTarget.dataset property.