VHaarish
VHaarish

Reputation: 81

Access Child component reference from Parent Component

I am new to react and I am trying to access a child component reference from a callback method in the parent component. When I try to access the reference, I am seeing the reference as null.

Parent Component

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import ChildComponentA from '../ChildComponentA';
import ChildComponentB from '../ChildComponentB’;

export default function ParentComponent(props) {

 const calendarRef = React.createRef();

const handleYearClick = (value) => {
    // const ref = React.createRef();
    console.log('click:', value, calendarRef);
    // setSelectedView('month');
    // const calendarApi = calendarRef.current.getApi();
};
const handleFilterEvent = (value) => {
const calendarApi = calendarRef.current.getApi();
if (value.includes('next')) calendarApi.next();
if (value.includes('prev')) calendarApi.prev();
}

return (

<section>

<ChildComponentA
    defaultView="dayGridMonth"
    eventData={allEvents}
    calendarRef={calendarRef}
     currentLang={currentLang}
/>
<ChildComponentB
 legendLabels={calendarLabels}
 currentYear={currentYear}
 yearEvents={allEvents}
onClick={handleYearClick}

/>
<ChildComponentC
 onClick={handleFilterEvent}
disableNextButton={disableNextButton}
disablePrevButton={disablePrevButton}

/>

<section/>
);

I am using the full calendar libary inside my ChildComponentA and I am trying to access the calendar Api from the parent.

The code in my child component A is,

export default function ChildComponentA(props) {
const {
    eventData,
    defaultView,
    calendarRef,
    currentLang,
  } = props;
  return (
    <section className={rootClass}>
      <FullCalendar
        ref={calendarRef}
        plugins={[dayGridPlugin]}
        initialView={defaultView}
        nowIndicator
        editable
        headerToolbar={false}
        weekNumbers
        contentHeight="auto"
        events={eventList}
        dayMaxEventRows
        views={eventTimeGrid}
        eventOrder="-start"
        eventClick={(event) => handleEventClick(event.event)}
        locale={currentLang}
      />
</section>
);

}

EDITED: Adding ChildComponentB code,

export default function ChildComponentB(props) {

const MONTHNAMES = ['January', 'February', 'March', 'April', 'May', 'June','July', 'August', 'September', 'October', 'November', 'December',];

const customDayClick = (date, events) => {
    if (date) {
      const yearNum = moment(date.date).month();
      const month = MONTHNAMES[yearNum];
      const goToDate = `${currentYear}-${month}-01`;
      onClick(goToDate);
    }
    if (events) {
      console.log('events:', events);
    }

    return null;
  };


return (
    <>
      <section className={rootClass}>
        <Calender
          id="yearCalendar"
          allowOverlap
          displayHeader={false}
          dataSource={eventDataSource}
          displayWeekNumber={false}          
          onDayClick={customDayClick}
          year={currentYear}
          language={currentLang}
        />
);
}

When I console log calendarRef inside handleYearClick in the parentComponent, I see it as null . ({current: null} current: null). But when I try the same inside the handleFilterEvent method which is a callback from ChildComponentC, I see the reference of full calendar like this {current: FullCalendar}. How do I get the reference of FullCalendar inside handleYearClick. What am i missing ? It would be great if some one can help me resolve this. Thank you in advance.

Upvotes: 0

Views: 245

Answers (1)

farvilain
farvilain

Reputation: 2562

So you can just pass the handleYearClick to the child component.

export default function ParentComponent(props) {

    const handleYearClick = (date) => {
        console.log('Want to go to date:', date);
    };

    return ( <ChildComponentB [...] onClick={handleYearClick} /> );
}
function ChildComponentB({handleYearClick}) {

    const customDayClick = (date, events) => {
        if (date) {
            const goTo = moment(date.date).format('YYYY-MMMM-01');
            handleYearClick(goTo);
        }
    };


    return ( <Calender onDayClick={customDayClick} [...] /> );
}

Upvotes: 1

Related Questions