Header

Crédit: Y. Alsberge

28-10-2020
Allow references between 2 components – React

Introduction

For a project, I was trying to have 2 different components interact with each other. Concretely, I had 2 date pickers and I wanted to ensure only one was open at a time…
The way to do it was to ensure that on the opening of one, I was closing the other one.

Context and Target

The context and target is then the following:

1...
2<DatePicker id={1} onDisplay={closeAllOtherDayPickers}>
3<DatePicker id={2} onDisplay={closeAllOtherDayPickers}>
4...

Problem

Being new to React, I was trying to reference one component to the other using variables declaring the components such as:

1...
2let datePicker1 = <DatePicker onDisplay={() => closeDatePicker(datePicker1)}>
3let datePicker2 = <DatePicker onDisplay={() => closeDatePicker(datePicker1)}>
4...
5return ( //I'm in a function component
6    ...
7    {datePicker1}
8    {datePicker2}
9    ...
10)

Unfortunately, it was not working…

Solution

I eventually found my salvation in refs (see React refs).
By using those refs, I was able to generate a reference to the other component and be able to act on it from the first component.

It went eventually like this:

1...
2let refDatePicker1 = useRef();
3let refDatePicker2 = useRef();
4...
5return( //I'm in a function component
6...
7    <DatePicker ref={refDatePicker1} onDisplay={() => closeDatePicker(refDatePicker2)}>
8    <DatePicker ref={refDatePicker2} onDisplay={() => closeDatePicker(refDatePicker1)}>
9...
10)

I know it’s optimizable but for a first attempt, it introduces me to the ref for me to manage to get out of my issue.