Home > OS >  How can I access variables in children components from parent in React?
How can I access variables in children components from parent in React?

Time:11-04

I'm trying to learn React through building out a form/calculator type app. Im learning that React is unidirectional and I can't seem to find the way to work with this. I am trying to make a table that accepts input values about patients changing care, then calculates an acuity(difficulty) level and uses that number to total all acuity on the unit and decide how many staff are needed per shift.

So, I used a component that builds each table row so that I could create random ages and random names from an api, and reduce repetitiveness. Then that component allows the user to choose changing levels of care. How can I get the acuity score from each row in Patient.js component back to the parent lvl so that I can use it to calculate the cumulative acuity level for all patients? I'm very confused when it comes to understanding states. Thanks!

//----------------------Patient.js-------------------------
import React, { useState} from "react";
import FakePatient from "./PtNameGenerator";
import AgeNumber from "./AgeGenerator";

function Patient(props) {
    const [totalAcuity, setTotalAcuity] = useState(0);
    const [assistance, setAssistance ] =useState('');
    const [oriented, setOriented ] =useState('');
    const [incontinent, setIncontinent ] =useState('');
    const [intubated , setIntubated ] =useState('');

    var acuity = 0;

    if (assistance === 'ind') {
        acuity  = 1;
    } else if (assistance === 'sba') {
        acuity  = 2;
    } else if (assistance === '1pa') {
        acuity  = 3;
    } else if (assistance === '2pa') {
        acuity  = 4;
    } else {
        acuity = 0;
    }

    if (oriented === "4") {
        acuity  = 1;
    } else if (oriented === '3') {
        acuity  = 2;
    } else if (oriented === '2') {
        acuity  = 3;
    } else if (oriented === '1') {
        acuity  = 4;
    } else {
        acuity = 0;
    }

    if (incontinent === "y") {
        acuity  = 2;
    } else if (assistance === 'n') {
        acuity  = 1;
    } else {
        acuity = 0;
    }

    if (intubated === "y") {
        acuity  = 4;
        
    } else if (intubated === 'n') {
        acuity  = 1;
    } else {
        acuity = 0;
    };


    return <tr className="Patient-row">
        <td className="Room-number">
            {props.room}
        </td>
        <td>
            <FakePatient />
        </td>
        <td>
            <p><AgeNumber/></p>
        </td>
        <td>
            <select name="assistance" onChange={event => setAssistance(event.target.value) }>
                <option value="na">Select</option>
                <option value="ind">Ind</option>
                <option value="sba">SBA</option>
                <option value="1pa">1PA</option>
                <option value="2pa">2PA</option>
            </select>    
        </td>
        <td>
            <select name="oriented" onChange={event => setOriented(event.target.value) } >
                <option value="4">x4</option>
                <option value="3">x3</option>
                <option value="2">x2</option>
                <option value="1">x1</option>
            </select>    
        </td>
        <td>            
            <select name="incontinent" onChange={event => setIncontinent(event.target.value) }>
                <option value="n">N</option>
                <option value="y">Y</option>
            </select>   
        </td>
        <td>            
            <select name="intubated"  onChange={event => setIntubated(event.target.value) }>
                <option value="n">N</option>
                <option value="y">Y</option>
            </select>   
        </td>
        <td className="Acuity-Score">            
              <p className="AcuityScoreResult">
                { acuity }
            </p>
        </td>
    </tr>;
};

export default Patient;




//----------------------App.js-------------------------
import React, { useEffect, useState } from 'react'
import './css/style.css';
import './css/reset.css';
import logo from "./assets/logo.svg";
import Patient from './Components/Patient';




function App() {

  const [acuity, setacuity] = useState(0);
  const [nurse, setnurse] = useState(0);
  
  /*
  const arr = document.querySelectorAll('.AcuityScoreResult');
  Array.from(arr).forEach(el => {
      let acuityrow = parseInt(el.innerHTML);
      setacuity(prevacuity => prevacuity   acuityrow);
  });
  */
  //when generate clicked
  const renderScoreTotal = () => {
    console.log(nurse);
  }




  return (
    <div className="App">
      <main>
        <section className="Left_col Padding">
          <img className="Center" src={ logo } alt="" />
          <h3>Staffing Matrix</h3>
          <h2>My Units</h2>
          <hr />
          <ul>
            <li className="Active-unit">2N Med/Surg</li>
            <li>4N Behavioral Health</li>
            <li>Emergency Department</li>
            <li>8E Oncology</li>
            <li>7SW Neuro ICU</li>
            <li>8NW Neonatal ICU</li>
          </ul>
          <button className="Logout-btn">Log Out</button>
        </section>
        <section className="Upper_col Padding">
          <div className="Date-container">
            <div className="Day">Thursday,</div>
            <div className="Date">November 2nd 2021</div>
          </div>
          <div>
            <h2 className="Hospital-title">Sedona Medical Center</h2>
            <h3 className="Unit-title Active-unit">Medical Surgical Unit</h3>
          </div>
        </section>
        <section className="Content_container Padding">
          <table>
            <thead>
              <tr>
                <th>Room #</th>
                <th>Name</th>
                <th>Age</th>
                <th>Assistance</th>
                <th>Oriented</th>
                <th>Incontinent</th>
                <th>Intubated</th>
                <th>Acuity Score</th>
              </tr>
            </thead>
            <tbody>
              < Patient room={401} />
              < Patient room={402} />
              < Patient room={403} />
              < Patient room={404} />
              < Patient room={405} />
              < Patient room={406} />
              < Patient room={407} />
              < Patient room={408} />
              < Patient room={409} />
              < Patient room={410} />
              < Patient room={411} />
              < Patient room={412} />
              < Patient room={413} />
              < Patient room={414} />
              < Patient room={415} />
              < Patient room={416} />
            </tbody>
          </table>
          <button onClick={renderScoreTotal} className="Generate-btn">
            Generate
        </button>
          <section className="Staff-ratios">
            <div className="Staff-card">
              <p className="Staff-title">Nurse</p>
              <p className="Staff-number">{ nurse }</p>
            </div>
            <div className="Staff-card">
              <p className="Staff-title">CNA</p>
              <p className="Staff-number">3</p>
            </div>
            <div className="Staff-card">
              <p className="Staff-title">Social Work</p>
              <p className="Staff-number">2</p>
            </div>
            <div className="Staff-card">
              <p className="Staff-title">PT/OT</p>
              <p className="Staff-number">2</p>
            </div>
            <div className="Staff-card">
              <p className="Staff-title">EVS</p>
              <p className="Staff-number">2</p>
            </div>
            <div className="Staff-card">
              <p className="Staff-title">Provider</p>
              <p className="Staff-number">2</p>
            </div>
          </section>
        </section>
      </main>
    </div>
  );
}

export default App;


CodePudding user response:

One way to do it is by using a value cache. you can use something like redux to maintain a set of global variables (value cache) that you can access from anywhere. React will automatically re-render corresponding UI components when values change.

More info in their website - https://redux.js.org/introduction/getting-started

However, if all your components are in one page, it's simpler to use useEffect react hook

More info in their website - https://reactjs.org/docs/hooks-reference.html#useeffect

CodePudding user response:

For these kinds of libraries, your mantra should be "props down, events up". You pass props to children and attach event listeners to the children in order for them to tell you that things have changed. The host (parent) component then decides what to do with the event data. Perhaps an onAccuityChange listener that you pass to Patient that will be called when it changes.

Alternatively, calculate the value in the host and pass it to the child.

  • Related