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.

Categories
React Answers

How to Access Nested Messages with react-intl?

Sometimes, we want to access nested messages with react-intl.

In this article, we’ll look at how to access nested messages with react-intl.

Access Nested Messages with react-intl

To access nested messages with react-intl, we can flatten the messages object into an object without nested propeties.

We can use the flatten function from the flat NPM package to do this.

For instance, we write:

import React from "react";
import flatten from "flat";
import { IntlProvider, FormattedMessage } from "react-intl";

const messages = {
  message: "some message",
  nested: {
    anotherMessage: "another message"
  }
};

export default function App() {
  return (
    <IntlProvider messages={flatten(messages)} locale="en" defaultLocale="en">
      <p>
        <FormattedMessage id="nested.anotherMessage" />
      </p>
    </IntlProvider>
  );
}

We have the messages object with a nested message.

Then to access nested.anotherMessage, we call the flatten function with messages and then we set that as the value of the messages prop of IntlProvider.

And then we set the id prop of FormattedMessage to nested.anotherMessage to show the message.

Therefore, we should see another message on the screen.

Conclusion

To access nested messages with react-intl, we can flatten the messages object into an object without nested propeties.

We can use the flatten function from the flat NPM package to do this.

Categories
React Answers

How to Make React Portal Work with React Hooks?

Sometimes, we want to make React Portal work with React Hooks.

In this article, we’ll look at how to make React Portal work with React Hooks.

Make React Portal Work with React Hooks

To make React Portal work with React Hooks, we can create a portal component with the ReactDOM.createPortal method.

For instance, we write:

import React from "react";
import ReactDOM from "react-dom";

export const Portal = ({
  children,
  className = "root-portal",
  element = "div"
}) => {
  const [container] = React.useState(() => {
    const el = document.createElement(element);
    el.classList.add(className);
    return el;
  });

  React.useEffect(() => {
    document.body.appendChild(container);
    return () => {
      document.body.removeChild(container);
    };
  }, [container]);

  return ReactDOM.createPortal(children, container);
};

export default function App() {
  return (
    <div>
      <Portal>hello world</Portal>
    </div>
  );
}

We create the Portal component that takes the children, className, and element props.

In it, we create the container element with the useState hook.

We pass in a function that calls docuemnt.createElement and returns the element that’s created.

We take the element prop to create the element and so we create a div by default.

Also, we call el.classList.add to add the class attribute to the element and set it to className.

Then in the useEffect hook callback, we call document.body.appendChild to append the container to the body.

And then we return the portal created with ReactDOM.createPortal created with children and container.

In App, we use Portal to add a div into the body element.

Conclusion

To make React Portal work with React Hooks, we can create a portal component with the ReactDOM.createPortal method.

Categories
React Answers

How to Map a Dictionary to Components in React?

Sometimes, we want to map a dictionary to components in React.

In this article, we’ll look at how to map a dictionary to components in React.

Map a Dictionary to Components in React

To map a dictionary to components in React, we can use the Object.entries to return an array of key-value pair arrays.

Then we can call map on that to map those entries to components.

For instance, we write:

import React from "react";

const options = {
  close: "Close",
  submit: "Submit",
  print: "Print"
};

export default function App() {
  return (
    <div>
      {Object.entries(options).map(([key, value]) => (
        <button key={key}>{value}</button>
      ))}
    </div>
  );
}

to call Object.entries on the options object to return an array of key-value pair arrays.

Then we call map with a callback that takes the key-value pair array and destructure it in to key and value.

Then we return a button with the key prop set to key and value used as the text content of the button.

Now we should see the Close, Submit, and Print buttons displayed.

Conclusion

To map a dictionary to components in React, we can use the Object.entries to return an array of key-value pair arrays.

Then we can call map on that to map those entries to components.