0

I have a time component that has four input fields with names fromHour, fromMinute, toHour and toMinute. I was able to make the component and it works perfectly fine, but right now all data of time component are declared inside it which makes it difficult to use it anywhere.

I want to call this component as child component and pass data and handle from parent to child. How can I proceed?


import { useState } from 'react';
import './App.css';
import TimeComponent from './TimeComponent';

function App() {
  const [sundayArray, setSundayArray] = useState([
    {
      fromHour:"2",
      toHour:"4",
      fromMinute:"0",
      toMinute:"0"
    }
  ]);
  return (
    <div className="container-fluid">
      <div className="col-md-12 p-4">
        <div className="row">
          {
            sundayArray.map((item, index) =>
            (
              <TimeComponent key={index} />
            ))
          }
          <div className='col-md-3'>
            <button name='button' className='btn btn-info' type='button' onClick={() => { setSundayArray(sundayArray.concat({fromHour:"1",toHour:"2",fromMinute:'0',toMinute:'0'})) }}>Add</button>

          </div>
        </div>
      </div>
      <div className='col-md-12 text-center p-2'>
        <button type='button' className='btn btn-danger'>Submit</button>
      </div>
    </div>
  );
}

export default App;

What I want is, every time component data comes inside the sundayArray state variable as soon as the user perform any action. I do not provide the timeComponent code as it is more than 100 lines.

halfer
  • 19,824
  • 17
  • 99
  • 186
Pranay kumar
  • 1,983
  • 4
  • 22
  • 51
  • so do you want to access the `sundayArray` state from inside `TimeComponent`? – cSharp Apr 13 '22 at 05:55
  • Yes, i want all the input fields of timeComponent managed with the Sunday array, for example when user change value of fromHour input field of timeComponent, its values save in the sundayArray – Pranay kumar Apr 13 '22 at 05:57
  • [This thread](https://stackoverflow.com/questions/35537229/how-can-i-update-the-parents-state-in-react?rq=1) will help you in your case I think. There is an answer with guidance to setState of a component from its children. – cSharp Apr 13 '22 at 06:16
  • You should share your `TimeComponent` too, that would help to see how you construct your states @Pranaykumar – Nick Vu Apr 13 '22 at 08:10
  • Could you provide the `TimeComponent` as well please ? – Lukas Laudrain Apr 15 '22 at 17:18

0 Answers0