Search code examples
reactjsmailto

React open mailto E-Mail client onClick with body from textarea


This sounds like it must have been asked before but I could only find how to do this in react native but I could not find how it's done in normal react for web. Preferably not with an a tag or Link tag that needs to be styled.

Here some code to illustrate what I want to do:

const onClickMailtoHandler = () => {
    //TODO: open default e-mail client e.g. via mailto link with text from (state) variable as body
}

<Button onClick={onClickMailtoHandler}>Send E-Mail</Button>

Here is how to do a mailto link in HTML:

<a href="mailto:[email protected]?body=My custom mail body">E-Mail to Max Mustermann</a>

Solution

  • I ended up creating a component similar to what @GitGitBoom suggested in the comments.

    Here for future Seekers:

    import React from "react";
    import { Link } from "react-router-dom";
    
    const ButtonMailto = ({ mailto, label }) => {
        return (
            <Link
                to='#'
                onClick={(e) => {
                    window.location.href = mailto;
                    e.preventDefault();
                }}
            >
                {label}
            </Link>
        );
    };
    
    export default ButtonMailto;
    

    Use it like this:

    <ButtonMailto label="Write me an E-Mail" mailto="mailto:[email protected]" />