Components and containers as variables in ReactDOM.render()

I’m currently taking the React course. I’ve had this question all along, but I got to a place in my learning where I went to try something only for it to not work–though my guess it should.

My question does not arise from this lesson per se. I could have asked this question much earlier in my learning journey.

Anyway, can I assign a Component instance to a variable, and a React container to a different variable, as so?

// As seen in the lesson(s) so far
ReactDOM.render(
	<TodaysPlan />,
	document.getElementById('app')
);

// Refactored
let component = <TonightsPlan />;
let container = document.getElementById('app');

ReactDOM.render(component, container);

Do these do the same thing? Is this bad practice? Will it or will it not work?

My sense as to why it doesn’t work–at least in that lesson I tried it on–is because the testing or whatever is going on behind the scenes is looking specifically for the format seen at the top of the code block above.

Technically, that’s already how it’s done with functional components. For example, in a different file, you might have:

export default const TonightsPlan = () => {
    return (
        <h1>Tonight's Plan: blahblahblah</h1>
    )
}

And at the top of the rendering file, you would have something like:

import TonightsPlan from './components/TonightsPlan'

But to more directly answer your question, there’s no need for that refactoring because of how it’s currently done.

Thank you for your response!

What about in terms of readability? Best practices? Is one ‘better’ than the other? Why? WiIl my refactor work in an environment that isn’t sandboxed?

In terms of readability, I prefer the normal way because it’s clear that what is being rendered is a component, due to the use of angled brackets. This also fits better with the JSX used in React which is meant to look like HTML elements.

Also, while your example is trivial, trying to refactor elements into variables would just be more code in the end, and keeping things simple in coding is a balance of not repeating yourself and making code that’s readable - code which suggests what is being done (e.g. with variable naming schemes and straightforward higher-order functions where for loops are not strictly necessary).

Thank you that is helpful!

Sometimes passing Components as props can be helpful. But maybe in your case, rendering children might help in your case already? That would be the better practice, if you only want to pass children:

function declaration:

function ParentComponent({ children }) {
  return (<div className="wrapper">
    { children }
  </div>)
}

usage:

<ParentComponent>
  <h1>I will be rendered as a Child of the ParentComponent</h1>
</ParentComponent>

rendered html:

<div className="wrapper">
    <h1>I will be rendered as a Child of the ParentComponent</h1>
</div>
1 Like