GucciProgrammer
GucciProgrammer

Reputation: 191

Is it possible to have a 'static' react component that can be used globally every page

The case I have is I require a react component that can be used in every page (without replacing the current page and overlaying this component on the page). I understand I could include this component in the render() of every page but I have 1000+ pages and that wouldn't be very scalable. I was thinking if it is possible to have a 'static' react component which is accessible by every page. I am new to react and didn't find any such example online. Thanks a bunch!

Upvotes: 1

Views: 1767

Answers (1)

Chris
Chris

Reputation: 59531

Yes, this is definetly possible. Though there are a few options, and the right one would greatly depend on your application. It's hard to say what you need without any code or example, but here are a few suggestions anyway:


What you need to do is first import that component into each of the pages you want to load it in. Let's assume this global component is in a separate file called GlobalComponent.js and is in the same directory.

import GlobalComponent from ./GlobalComponent (note that you can omit the .js from filename)

Then in your render function you just write like this:

render() {
  return (
    ...

    <GlobalComponent />

    ...
  );
}

And that's it! You can pass in props to it if you want like this:

<GlobalComponent className="style1" />

and even give it children

<GlobalComponent>Hello World!</GlobalComponent>

If you don't use JSX, you can create this element like this:

React.createElement(GlobalComponent, {className: 'style1'}, 'Hello world!')

where the 2nd parameter is the props and the 3rd the children.

Both methods would render this:

<GlobalComponent class="style1">Hello world!</GlobalComponent>

If you don't want to do this for all your files, then you could alternatively just paste that html before the root react component.

For example:

<body>
<div class="global-component"></div>
<div id="main">
  //react stuff goes here. "global-component" is on all pages.
</div>

ReactDOM.render(reactElement, document.getElementById('main));


Another option is like the first option, but you pass in another React Component to the top-level parent React Element and just render it where needed. You can keep passing it on and implemented where you want it. It depends on your application.


If you are using react-router you can do something like @The suggested as well.

Upvotes: 1

Related Questions