Home > Software engineering >  React refs email form
React refs email form

Time:06-18

I’m a music engineer building a personal website using react. I’m tryna make a contact form where the person types a subject in an input field, a message in a textarea, then hits a “reach out” button and their mail client opens with the subject and body of the e-mail populated with the contents of the input field and textarea respectively. The trouble is I can’t seem to pass data from my react refs to the window.open function…the email pulls up with the subject reading “subject” and the body reading “body”. Relevant code follows, any help would be greatly appreciated

import React, { useRef } from 'react';
import './index.css';
import * as parts from   './UIComponents.js'

const subjectRef = useRef(null);
const messageRef = useRef(null);

export class Email extends  React.Component {
      goButton(i) {
          return(<parts.ButtonFactory onClick={() => this.go()} value={i} />);
  }
      go() {
         let subject = subjectRef.current.value;
         let body = messageRef.current.value;
         window.open('mailto:[email protected]?subject=subject&body=body');
  }
      render() {
        return (
          <div className="email-form">
          <div className="container">
          <div className="input-group">
            <label>Your Name:</label>
            <input type="text" ref={subjectRef} />
            <br />
            <label>Detailed Message:</label>
           <textarea rows="8" ref={messageRef} />
          </div>
          <div className="btn-group">
            {this.goButton('REACH OUT')}
          </div>
          </div>
          </div>
    );
}
}

CodePudding user response:

Problem is in that your go function is passing "body" and "subject" as string and not as variables. That's why your mail client is open with such values.

If you want to pass variables you can use string templates

go() {
  let subject = subjectRef.current.value;
  let body = messageRef.current.value;
  window.open(`mailto:[email protected]?subject=${subject}&body=${body}`);
}
  • Related