Home > Software engineering >  How do I send an array to a child component in React?
How do I send an array to a child component in React?

Time:01-13

I want to send the array inputArrival and inputBurst to the child component Barchart.js. But whenever I do this only the first element which I enter is being sent and not the other items. Basically what I want is that as the data is being entered into the Entrytable.js it is instantly reflected. EntryTable.js

import React,{useState} from 'react';
import './tableEdit.css';
import Barchart from './Barchart';

const EntryTable = (props) => {
    const entry = props.numOfEntries;
    const [inputArrival, setInputArrival] = useState(Array(entry).fill(""));
    const [inputBurst, setInputBurst] = useState(Array(entry).fill(""));
  
  
    function changeArrival(index) {     
      return (e) => {
       setInputArrival((values) =>
          values.map((value, i) => (i === index ? e.target.value : value)));};
    }
    function changeBurst(index) {
      return (e) => {  
     setInputBurst((values) =>
          values.map((value, i) => (i === index ? e.target.value : value))         
        );
      };
    }
    const ArrayEntry = Array.from({ length: entry}).map((_, i) => (
      <tr key={i}>
          <td >P{i}</td>
          <td >
            <input            
              type="number"
              value={inputArrival[i]}
              onChange={changeArrival(i)}             
            />
            ms
          </td>
          <td >
            <input            
              type="number"
              value={inputBurst[i]}
              onChange={changeBurst(i)}            
            />
            ms
          </td>
        </tr>
    ));
     return (
      <div  c>
        <table>
          <thead>
            <tr>
              <th>Process</th>
              <th>Arrival Time</th>
              <th>Burst Time</th>
            </tr>
          </thead>
          <tbody>{ArrayEntry}</tbody>
        </table>
        <button>Click Me</button>
        <Barchart selected_val={entry} arrivalArray={inputArrival} ></Barchart>
      </div>
    );
  };
export default EntryTable

Barchart.js

import React,{useState,useEffect} from 'react'
const Barchart=(props)=>{    
  const sel = props.selected_val; 
 var ar1=props.arrivalArray;
 console.log(ar1);
}export default Barchart;

Screenshot 1

CodePudding user response:

As far as i got your question, im not sure where is the problem:

  • What ive done?

First: As Tasos said converted all the variables to let;

Second: Assigned a value of 5 for the const entry enter image description here

The only difference is returning something in Barchart.js. Maybe try to return null in Barchart.js, it might throw a silent error.

I recommend using a linter also for code styling.

  •  Tags:  
  • Related