Home > Software design >  Trying to reformat this class into a function
Trying to reformat this class into a function

Time:11-10

I'm integrating a Twilio API and want to know how I can change this class into a function using hooks. I've learning this method before, but it's a bit tricky. Heres the code. The purpose of this code is so I can send a text message from my application.


import React, { Component } from 'react';


class TextForm extends Component {

  state = {
    text: {
      recipient: '',
      textmessage: ''
    }
  }

  sendText = _ => {
    const { text } = this.state;
    //pass text message GET variables via query string
    fetch(`http://localhost:4000/send-text?recipient=${text.recipient}&textmessage=${text.textmessage}`)
    .catch(err => console.error(err))
  }


  render() {
    const { text } = this.state;
    const spacer = {
      margin: 8
    }
    const textArea = {
      borderRadius: 4
    }

    
    return (
      <div className="App">
        <header className="App-header">
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <div style={{ marginTop: 10 }} >
          <h2> Send Text Message </h2>
          <label> Your Phone Number </label>
          <br />
          <input value={text.recipient}
            onChange={e => this.setState({ text: { ...text, recipient: e.target.value } })} />
          <div style={spacer} />
          <label> Message </label>
          <br />
          <textarea rows={3} value={text.textmessage} style={textArea}
            onChange={e => this.setState({ text: { ...text, textmessage: e.target.value } })} />
          <div style={spacer} />
          <button onClick={this.sendText}> Send Text </button>
        </div>
      </div>
    );
  }
}

export default TextForm;

CodePudding user response:

Setup a functional component

const TextForm () => {
      const [text, setText] = React.useState({
     {
          recipient: '',
          textmessage: ''
        }
    });
     const  sendText = ()=> {
        //pass text message GET variables via query string
        fetch(`http://localhost:4000/send-text?recipient=${text.recipient}&textmessage=${text.textmessage}`)
        .catch(err => console.error(err))
      }

    const spacer = {
      margin: 8
    }
    const textArea = {
      borderRadius: 4
    }

     return ( 
     <div className="App">
            <header className="App-header">
              <h1 className="App-title">Welcome to React</h1>
            </header>
            <div style={{ marginTop: 10 }} >
              <h2> Send Text Message </h2>
              <label> Your Phone Number </label>
              <br />
              <input value={text.recipient}
                onChange={e => setText({ text: { ...text, recipient: e.target.value } })} />
              <div style={spacer} />
              <label> Message </label>
              <br />
              <textarea rows={3} value={text.textmessage} style={textArea}
                onChange={e => setText({ text: { ...text, textmessage: e.target.value } })} />
              <div style={spacer} />
              <button onClick={sendText}> Send Text </button>
            </div>
          </div>
     );
    }
    
    export default TextForm

CodePudding user response:

Mostly all the parts are there - you just have to organise them. You no longer have to rely on this - you can just add functions inside the component to deal with the uploads and the state changes.

(Note: I did add some fieldsets to your JSX as I think they look nice.)

const { useState } = React;

function TextForm() {

  // Set up the state with an empty object
  const  [text, setText] = useState({});

  // I'm only logging the state here as I don't have
  // API access for this working demo
  function sendText() {
    console.log(text);
    // const params = `${text.phonenumber}&textmessage=${text.message}`;
    // fetch(`http://localhost:4000/send-text?${params}`)
    // .catch(err => console.error(err))
  }

  // Grab the name and value from the input
  // that has been clicked, and use that information
  // to update the state
  function handleChange(e) {
    const { name, value } = e.target;
    setText({ ...text, [name]: value });
  }

  // Make sure that for each input you include
  // a name attribute
  return (
    <div>
      <fieldset>
       <legend>Phone Number</legend>
        <input
          name="phonenumber"
          type="tel"
          value={text.phonenumber}
          onChange={handleChange}
        />
      </fieldset>
      <fieldset>
        <legend>Message</legend>
        <textarea
          name="message"
          rows={3}
          value={text.message}
          onChange={handleChange}
        />
      </fieldset>
      <br />
      <button onClick={sendText}>Send Text</button>
    </div>
  );

}

ReactDOM.render(
  <TextForm />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

first for functional component if you wanna create state you need to import useState from react, then convert your state first:

from this:

state = {
    text: {
      recipient: '',
      textmessage: ''
    }
  }

To This functional component useState

const [text, setText] = useState({
    recepient: "",
    textMessage: ""
  });

convert your method into function from this:

sendText = _ => {
    const { text } = this.state;
    //pass text message GET variables via query string
    fetch(`http://localhost:4000/send-text?recipient=${text.recipient}&textmessage=${text.textmessage}`)
    .catch(err => console.error(err))
  }


  render() {
    const { text } = this.state;
    const spacer = {
      margin: 8
    }
    const textArea = {
      borderRadius: 4
    }

To this function :

const sendText = (_) => {
    //pass text message GET variables via query string
    fetch(
      `http://localhost:4000/send-text?recipient=${text.recepient}&textmessage=${text.textMessage}`
    ).catch((err) => console.error(err));
  };

  const spacer = {
    margin: 8
  };
  const textArea = {
    borderRadius: 4
  };

and than last convert your return the full code is below:

import React, { useState } from "react";

const TextForm = () => {
  const [text, setText] = useState({
    recepient: "",
    textMessage: ""
  });

  const sendText = (_) => {
    //pass text message GET variables via query string
    fetch(
      `http://localhost:4000/send-text?recipient=${text.recepient}&textmessage=${text.textMessage}`
    ).catch((err) => console.error(err));
  };

  const spacer = {
    margin: 8
  };
  const textArea = {
    borderRadius: 4
  };

  return (
    <div className="App">
      <header className="App-header">
        <h1 className="App-title">Welcome to React</h1>
      </header>
      <div style={{ marginTop: 10 }}>
        <h2> Send Text Message </h2>
        <label> Your Phone Number </label>
        <br />
        <input
          value={text.recepient}
          onChange={(e) =>
            setText((prevText) => ({
              ...prevText,
              recepient: e.target.value
            }))
          }
        />
        <div style={spacer} />
        <label> Message </label>
        <br />
        <textarea
          rows={3}
          value={text.textMessage}
          style={textArea}
          onChange={(e) =>
            setText((prevText) => ({
              ...prevText,
              textMessage: e.target.value
            }))
          }
        />
        <div style={spacer} />
        <button onClick={sendText}> Send Text </button>
      </div>
    </div>
  );
};

export default TextForm;
  • Related