Categories
React Answers

How to Add a Click Handler to the Body Element from within a React Component?

Sometimes, we want to add a click handler to the body element from within a React component.

In this article, we’ll look at how to add a click handler to the body element from within a React component.

Add a Click Handler to the Body Element from within a React Component

To add a click handler to the body element from within a React component, we call the addEventListener method on document.body in the useEffect hook callback to starting listening to clicks on the body element when the component loads.

For instance, we can write:

import React, { useEffect } from "react";
export default function App() {
  useEffect(() => {
    const onClick = () => {
      console.log("body clicked");
    };
    document.body.addEventListener("click", onClick);

    return () => {
      document.body.removeEventListener("click", onClick);
    };
  }, []);

  return <div>hello world</div>;
}

to call the useEffect hook with a callback that calls document.body.addEventListener with 'click' and onClick to add the onClick function as the event listener for click events emitted from the body element.

Also, we return function that calls removeListener to remove the body click listener when the component is unmounted.

And we pass in an empty array as the 2nd argument of useEffect to run the useEffect callback only when the component mounts.

Now when we click on the body element, we should see 'body clicked' logged in the console.

Conclusion

To add a click handler to the body element from within a React component, we call the addEventListener method on document.body in the useEffect hook callback to starting listening to clicks on the body element when the component loads.

Categories
React Answers

How to Use the marked Markdown Library in React?

Sometimes, we want to use the marked Markdown library in our React app.

In this article, we’ll look at how to use the marked Markdown library in our React app.

Use the marked Markdown Display Component in React

To use the marked Markdown display component in our React app, we just call, the marked function that comes with the marked library to convert the Markdown string into an HTML string.

Then we can render the HTML string with dangerouslySetInnerHTML .

For instance, we can write:

import React from "react";
import marked from "marked";
export default function App() {
  const getMarkdownText = () => {
    const rawMarkup = marked("This is _Markdown_.", { sanitize: true   });
    return { __html: rawMarkup };
  };

  return <div dangerouslySetInnerHTML={getMarkdownText()} />;
}

We create the getMarkdownText function to convert the “This is _Markdown_.” Markdown string into an HTML string with the marked function.

And we set sanitize to true to escape any special characters.

Then we set the dangerouslySetInnerHTML prop of the div to the HTML string returned by the getMarkdownText function.

Conclusion

To use the marked Markdown display component in our React app, we just call, the marked function that comes with the marked library to convert the Markdown string into an HTML string.

Then we can render the HTML string with dangerouslySetInnerHTML .

Categories
React Answers

How to Create a Tooltip Div with React?

Sometimes, we want to create a tooltip div with React.

In this article, we’ll look at how to create a tooltip div with React.

Create a Tooltip Div with React

To create a tooltip div with React, we can set the onMouseOver and onMouseOut props to functions that set the hover state to true and false respectively.

And we can use the hover state to determine whether the tooltip div is displayed.

For instance, we can write:

import { useState } from "react";

export default function App() {
  const [hover, setHover] = useState();

  return (
    <div>
      <div
        onMouseOver={() => setHover(true)}
        onMouseOut={() => setHover(false)}
      >
        Hover
      </div>
      <div>
        <div style={{ display: hover ? "block" : "none" }}>
          this is the tooltip!!
        </div>
      </div>
    </div>
  );
}

We have the hover state that we created with the useState hook.

Then we add the onMouseOver and onMouseOut props to set hover to true and false respectively when those events are emitted on the outer div.

Next, we add the tooltip div by writing:

<div style={{ display: hover ? "block" : "none" }}>
  this is the tooltip!!
</div>

Now when we hover over the Hover text, we see the tooltip displayed.

Conclusion

To create a tooltip div with React, we can set the onMouseOver and onMouseOut props to functions that set the hover state to true and false respectively.

And we can use the hover state to determine whether the tooltip div is displayed.

Categories
React Answers

How to Show a Button on Mouse Enter with React?

Sometimes, we want to show a button on mouse enter with React.

In this article, we’ll look at how to show a button on mouse enter with React.

Show a Button on Mouse Enter with React

To show a button on mouse enter with React, we can set the onMouseEnter and onMouseLeave props to state change functions that determine when the button is shown.

For instance, we can write:

import { useState } from "react";

export default function App() {
  const [isMouseInside, setIsMouseInside] = useState();

  return (
    <div
      style={{ width: 200, height: 200 }}
      onMouseEnter={() => setIsMouseInside(true)}
      onMouseLeave={() => setIsMouseInside(false)}
    >
      {isMouseInside ? <button>Your Button</button> : null}
    </div>
  );
}

to create the isMouseInside state with the useState hook that determines when the button is shown.

Then we set the onMouseEnter prop to a function that calls setIsMouseInside with true to set isMouseInside to true .

Likewise, we set the onMouseLeave prop to a function that calls setIsMouseInside with false to set isMouseInside to false.

Then we only show the button when isMouseInside is true by writing:

{isMouseInside ? <button>Your Button</button> : null}

Conclusion

To show a button on mouse enter with React, we can set the onMouseEnter and onMouseLeave props to state change functions that determine when the button is shown.

Categories
React Answers

How to Use React-Intl in an Input Placeholder?

Sometimes, we want to use React-Intl in an input placeholder.

In this article, we’ll look at how to use React-Intl in an input placeholder.

Use React-Intl in an Input Placeholder

To use React-Intl in an input placeholder, we can use the intl.formatMessage method with an object that has the message ID we want to display set as the value of the id property of the object.

For instance, we can write:

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { IntlProvider } from "react-intl";
import App from "./App";

const lang = "en";
const messages = {
  en: {
    placeholderMessageId: "placeholder in english"
  },
  fr: {
    placeholderMessageId: "placeholder en fançais"
  }
};

const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <IntlProvider locale={lang} messages={messages[lang]}>
      <App />
    </IntlProvider>
  </StrictMode>,
  rootElement
);

App.js

import { useIntl } from "react-intl";

export default function App() {
  const intl = useIntl();

  return (
    <input placeholder={intl.formatMessage({ id: "placeholderMessageId" })} />
  );
}

We wrap the IntlProvider around the App component so that we can use the useIntl hook in App to get the placeholder message for the language set with formatMessage .

The locale is the locale of the language we want to display.

messages has the messages for each language.

In App , we set the placeholder prop of the input to the return value of intl.formatMessage({ id: “placeholderMessageId” }) to set the placeholder to the message that corresponds to the key placeholderMessageId .

Therefore, placeholder in english is displayed as the placeholder of the input since lang is 'en' and placeholderMessageId for en is placeholder in english .

Conclusion

To use React-Intl in an input placeholder, we can use the intl.formatMessage method with an object that has the message ID we want to display set as the value of the id property of the object.