Home > Enterprise >  Passing props - React
Passing props - React

Time:11-13

I have a problem I've been stuck on for a few hours now.

I have a component that when fired, it changes a const from "true" to "false". Using this information, I want to display a "sent" or "not sent" text div in another component.

For the life of me, I can not pass this prop into the other component.

I can not get the component ReadOnlyRow to read the prop sentStatus.

import React, { useState } from "react";


const TextForm = ({ contact, messageSent, props }) => {
  
  const [sentStatus, setSentStatus] = useState(true)
  const [sendTextText, setSendTextText] = useState("N/A")

  function sendText () {

    let phoneNumber = 1   contact.phoneNumber
    
    //pass text message GET variables via query string
    fetch(`http://localhost:4000/send-text?recipient=${phoneNumber}&textmessage=Dear ${contact.fullName}, Your liscnese is set to expre on 9/21`)
    .catch(err => console.error(err))
    console.log(contact.fullName)
    console.log(messageSent)
    
    console.log(sentStatus)
    setSentStatus(!sentStatus)
    
    if (sentStatus === true){
      setSendTextText('good')
      console.log("true")
    } else {
      setSendTextText('bad')
      console.log("false")
    }
    }


  return (
    <div>
    <button onClick={sendText}>Send</button>
    <h1>{contact.phoneNumber}</h1>
    </div>
    
  );
};

export default TextForm;

import React, { useState, Fragment, Component } from "react";
import { nanoid } from "nanoid";
import "./App.css";
import data from "./mock-data.json";
import ReadOnlyRow from "./components/ReadOnlyRow";
import EditableRow from "./components/EditableRow";
import Header from "./components/Header";
import TextForm from "./TextForm";

function App() {
  const [contacts, setContacts] = useState(data)
  const [messageSent, setMessageSent] = useState(12)
  
  const [addFormData, setAddFormData] = useState({
    fullName: "",
    address: "",
    phoneNumber: "",
    email: ""
  });
  

  // const [textItem, setSet] = useState({
  //   text: {
  //     recipient: 'gorge',
  //     textmessage: 'gorgeous'
  //   }
  // })

  

  const [editFormData, setEditFormData] = useState({
    fullName: "",
    address: "",
    phoneNumber: "",
    email: "",
  });

  const [editContactId, setEditContactId] = useState(null);

  const handleAddFormChange = (event) => {
    event.preventDefault();

    const fieldName = event.target.getAttribute("name");
    const fieldValue = event.target.value;

    const newFormData = { ...addFormData };
    newFormData[fieldName] = fieldValue;

    setAddFormData(newFormData);
  };
  

  const handleEditFormChange = (event) => {
    event.preventDefault();
    

    const fieldName = event.target.getAttribute("name");
    const fieldValue = event.target.value;

    const newFormData = { ...editFormData };
    newFormData[fieldName] = fieldValue;

    setEditFormData(newFormData);

    
  };

  const handleAddFormSubmit = (event) => {
    event.preventDefault();

    const newContact = {
      id: nanoid(),
      fullName: addFormData.fullName,
      address: addFormData.address,
      phoneNumber: addFormData.phoneNumber,
      email: addFormData.email,
    };

    const newContacts = [...contacts, newContact];
    setContacts(newContacts);
  };

  const handleEditFormSubmit = (event) => {
    event.preventDefault();

    const editedContact = {
      id: editContactId,
      fullName: editFormData.fullName,
      address: editFormData.address,
      phoneNumber: editFormData.phoneNumber,
      email: editFormData.email,
    };

    const newContacts = [...contacts];

    const index = contacts.findIndex((contact) => contact.id === editContactId);

    newContacts[index] = editedContact;

    setContacts(newContacts);
    setEditContactId(null);
  };

  const handleEditClick = (event, contact) => {
    event.preventDefault();
    setEditContactId(contact.id);

    const formValues = {
      fullName: contact.fullName,
      address: contact.address,
      phoneNumber: contact.phoneNumber,
      email: contact.email,
    };

    setEditFormData(formValues);
  };

  const handleCancelClick = () => {
    setEditContactId(null);
  };

  const handleDeleteClick = (contactId) => {
    const newContacts = [...contacts];

    const index = contacts.findIndex((contact) => contact.id === contactId);

    newContacts.splice(index, 2);

    setContacts(newContacts);
  };
  
  function status ({sentStatus}) {
    console.log(sentStatus)
  }

  
    return (
    <div className="app-container">
      <Header />
      <form onSubmit={handleEditFormSubmit}>
        <table>
          <thead>
            <tr>
              <th>Name</th>
              <th>Guard #</th>
              <th>Phone Number</th>
              <th>Employee ID</th>
              <th>Expiration Date</th>
              <th>Actions</th>
              <th>Was the text sent out?</th>
              <th>Was an SMS sent?</th>
            </tr>
          </thead>
          <tbody>
            {contacts.map((contacto) => (
              <Fragment>
                {editContactId === contacto.id ? (
                  <EditableRow
                    editFormData={editFormData}
                    handleEditFormChange={handleEditFormChange}
                    handleCancelClick={handleCancelClick}
                  />
                ) : (
                  <ReadOnlyRow
                    contact={contacto}
                    handleEditClick={handleEditClick}
                    handleDeleteClick={handleDeleteClick}
                    messageSent={messageSent}
                  />
                )}
              </Fragment>
            ))}
          </tbody>
        </table>
      </form>

      <h2>Add a Contact</h2>
      <form onSubmit={handleAddFormSubmit}>
        <input
          type="text"
          name="fullName"
          required="required"
          placeholder="Enter a name..."
          onChange={handleAddFormChange}
        />
        <input
          type="text"
          name="address"
          required="required"
          placeholder="Enter an addres..."
          onChange={handleAddFormChange}
        />
        <input
          type="text"
          name="phoneNumber"
          required="required"
          placeholder="Enter a phone number..."
          onChange={handleAddFormChange}
        />
        <input
          type="email"
          name="email"
          required="required"
          placeholder="Enter an email..."
          onChange={handleAddFormChange}
        />
        <button type="submit">Add</button>
      </form>
    </div>
  );
};

export default App;
import React, { useState } from "react";
import TextForm from "../TextForm";
import WasMessageSent from "./WasMessageSent";
import TextStatus from "./TextStatus";
import App from "../App";

const ReadOnlyRow = ({ contact, handleEditClick, handleDeleteClick, sentStatus, messageSent, sendo}, props) => {
  
  const [text, setText] = useState("yes")


  function status (){
    const gord = {sentStatus}
    console.log(gord)

  }

  

  return (
    <tr>
      <td>{contact.fullName}</td>
      <td>{contact.address}</td>
      <td>{contact.phoneNumber}</td>
      <td>{contact.email}</td>
      <td>
        <button
          type="button"
          onClick={(event) => handleEditClick(event, contact)}
        >
          Edit
        </button>
        <button type="button" onClick={() => handleDeleteClick(contact.id)}>
          Delete
        </button>
      </td>
      <td>
        <TextForm 
        contact={contact}
        status={sentStatus}
        />
        <button>Send Email</button>
      </td>
      <td>Did they update it yet?</td>
      <td>{messageSent}</td>
      <td>{text}</td>
      <td><button onClick={status}>statuschecker</button></td>
    </tr>
  );
};

export default ReadOnlyRow;

CodePudding user response:

Here is an exemple on how you can do it,

you create a state in the parent app, then you pass the state to the child component that needs it (ReadOnlyRow), and you pass the setState to the other child component (TextForm)

enter image description here

Here it is a simple demo, hopefully it will help you understand me better:

The App Component

import React, { useState } from "react";

import ReadOnlyRow from "./ReadOnlyRow";
import TextForm from "./TextForm";

function App() {
 
  const [sentStatus, setSentStatus] = useState(false)

  return (
    <div className="app-container">
     <TextForm setSentStatus={setSentStatus} />
     <ReadOnlyRow sentStatus={sentStatus} />
    </div>
  );
};

export default App;

The TextForm component

import React from "react";

const TextForm = ({ setSentStatus }) => {
  
  const sendText = () => {
    setSentStatus(true)
  }

  return (
    <div>
      <button onClick={sendText}>Send</button>
    </div>
  );
};

export default TextForm;

The ReadOnlyRow component

import React from "react";

const ReadOnlyRow = ({ sentStatus }) => {

  return (
   <p>
      {sentStatus ? 'sent' : 'not sent'}
   </p>
  );
};

export default ReadOnlyRow;
  • Related