Search code examples
reactjsreact-componentmailto

How to set mailto into a property of child react.js component


I am returning data from API in React.js, one property is 'email' of object 'user'. I would like to be able to click on the email address so a new email window addressed to that user pops up. I want the email address to appear in the 'to' input field.

I would like something like this: <a href="mailto:[email protected]">[email protected]</a> but for react.

I have been searching but I found this solution, this solution and this solution difficult to understand as they are written the old way or they are for react native only.

Someone suggested event this ...but how to apply it inside my component?

window.open('mailto:[email protected]?subject=Subject&body=Body%20goes%20here')

This is the child component:

const UserDetail = ({name, username, email, address, address2, city, phone, website, company, onClick}) => {
 
  return (
    <>
      <DetailCard>    
        <Name>{name}</Name>
        <Data>Username:{username}</Data>
        <Data>E-mail:{email}</Data>
        <Data>Adress:{address}</Data>
        <Data>Adress 2:{address2}</Data>
        <Data>City:{city}</Data>
        <Data>Phone number:{phone}</Data>      
        <Data>Website:{website}</Data>      
        <Data>Company:{company}</Data>
        <Button onClick={onClick}>close</Button>      
      </DetailCard>
    </>
  )}

Solution

  • Attach an onClick event handler to the e-mail field:

    const UserDetail = ({name, username, email, address, address2, city, phone, website, company, onClick}) => {
     
      function onEmailClick() {
          window.open(`mailto:${email}`);
      }
    
      return (
        <>
          <DetailCard>    
            ...
            <Data onClick={onEmailClick}>E-mail:{email}</Data>
            ...
          </DetailCard>
        </>
      )}