ReactJS - How to get a reference to the current element/component for further rendering?

Viewed 21

I'd like to pass as a variable, the JSX.Element of the current component being displayed.

In this example on CodeSandbox, a main menu navigates to an activity screen after a button click.

https://codesandbox.io/s/silly-moon-kbznm?file=/src/App.tsx

export default function App() {
  return (
    <div className="App">
        Header - hello I remain unchanged
        <div id="screen-container">
            <Menu />
        </div>
    </div>
  );
}

First, I use a div with an id as a main container after my header. Later, I'll use a navigateToElement() function to place JSX.Element in that container:

function navigateToElement(screen: JSX.Element) {
  ReactDOM.render(
    screen,
    document.getElementById("screen-container")
  );
}

The component appearing first inside the container div is <Menu/>:

export function Menu() {
  return (
    <div>
      <h1>I am the menu</h1>
      <button onClick={() => {
         navigateToElement(<Activity/>);
      }}>Start activity</button>
    </div>
  );
}

It displays one button that calls the navigateToElement() function to replace the <Menu/> by the <Activity/> component. The <Activity/> component contains a button to go back to the menu.

export function Activity() {
  return (
    <div>
      <h1>Activity screen</h1>
      <button onClick={() => {
         navigateToElement(<Menu/>);
      }}>Back to menu</button>
    </div>
  );
}

It works fine, but in the <Activity/> component, I've hardcoded to go back to <Menu/>. Would it be possible instead to go back to "where I come from"?

In that scenario:

    1. The menu displays.
  • 2a. The user clicks the button on the menu.
  • 2b. The menu's button handler gets a reference to itself and pass it to the Action component.

Something like:

var refToMenu = ..... reference to myself
navigateToElement(<Activity/>);
    1. The activity component displays
  • 4a. The user click the "back to menu" button
  • 4b. The activity component navigates to the menu referred through the variable.

navigateToElement(refToMenu);

Do you have any idea how to achieve this? Many thanks. John.

0 Answers
Related