user2840647 user2840647 - 2 months ago 10
React JSX Question

ReactRouter passing name of component

I'm trying to use ReactRouter in my application like so:

const App = () => (
<BrowserRouter>
<div>
<Match exactly pattern="/" render={() => (
<Redirect to="/dashboard" />
)} />
<Match exactly pattern="/dashboard" render={() => (
<DashboardPage content={Main} />
)} />
</div>
</BrowserRouter>
);

const DashboardPage = ({ content }) => (
<div>
<main>
{content}
</main>
</div>
);

const Main = () => (
<div>
<h2>Hello World</h2>
</div>
);


Unfortunately, the Main component isn't being rendered. The only way to render it is like so
<DashboardPage content={<Main />} />
whereas
<Match exactly pattern="/dashboard" component={Main} />
works just fine.

Answer

I was going to put this as a comment, but it needs formatting, so it gets to be an answer;

JSX is just a set of syntax around javascript. You're still writing javascript, and all the rules of javascript still apply.

Main is a function. If you type the name of a function, the result will be the function definition. But in order for a react class to create a component, you need to actually execute that function, not just output it's definition.

It's the same as console.log vs. console.log(). Type each into your console and see the difference. The first returns a function, the second gives you the return value of that function. For react components, the HTML result is the return value of the function.

In my opinion, the best way to modify your code would be as follows:

const DashboardPage = ({ Content }) => (
  <div>
    <main>
      <Content />
    </main>
  </div>

);

And be sure to capitalize Content when setting the props for DashboardPage as well.