Email link

React, Components · Nov 16, 2020

Renders a link formatted to send an email (mailto: link).

  • Use the email, subject and body props to create a <a> element with an appropriate href attribute.
  • Use encodeURIcomponent to safely encode the subject and body into the link URL.
  • Render the link with children as its content.
const Mailto = ({ email, subject = '', body = '', children }) => {
  let params = subject || body ? '?' : '';
  if (subject) params += `subject=${encodeURIComponent(subject)}`;
  if (body) params += `${subject ? '&' : ''}body=${encodeURIComponent(body)}`;

  return <a href={`mailto:${email}${params}`}>{children}</a>;
};
ReactDOM.createRoot(document.getElementById('root')).render(
  <Mailto email="foo@bar.baz" subject="Hello & Welcome" body="Hello world!">
    Mail me!
  </Mailto>
);

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • Automatic text linking

    Renders a string as plaintext, with URLs converted to appropriate link elements.

    React, Components · Nov 3, 2020

  • Tag input field

    Renders a tag input field.

    React, Components · Nov 25, 2020

  • Tabs

    Renders a tabbed menu and view component.

    React, Components · Oct 13, 2021