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.

Categories
React Answers

How to Play an MP3 Clip on Click in React?

Sometimes, we want to play an mp3 clip on click in React.

In this article, we’ll look at how to play an mp3 clip on click in React.

Play an MP3 Clip on Click in React

To play an mp3 clip on click in React, we can use the Audio constructor to create an audio element with the MP3 file URL.

Then we call play on the created object to play the audio clip.

For instance, we write:

import React from "react";

export default function App() {
  const audio = new Audio(
    "https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
  );

  const start = () => {
    audio.play();
  };

  return (
    <div>
      <button onClick={start}>Play</button>
    </div>
  );
}

We create the audio object with the Audio constructor with the MP3 file URL as its argument.

Then we call audio.play in the start function to play the audio clip when we click Play since we set start as the value of the onClick prop as the button.

Conclusion

To play an mp3 clip on click in React, we can use the Audio constructor to create an audio element with the MP3 file URL.

Then we call play on the created object to play the audio clip.