Adding React Components
This guide covers how to add React components to your Gatsby site.
React components are prebuilt elements or groups of elements that can be used to split your User Interface (UI) into independent, reusable pieces. There are multiple types of components you can write: this guide covers functional components. For more in-depth information on writing React components including classes, check out the React documentation.
For example, you could use a component for Buttons on your site. This would enable them to be used multiple times across pages with different labels or actions each time.
In Gatsby, when using React components, you can import and use them like you would in a React application. Here’s an example of the Gatsby Link component in action, which brings with it extra functionality for performance:
Just like React, Gatsby also supports third-party components and libraries. You can install a third-party component or library via your package manager. We tend to favour and use npm and we will reflect this in our examples.
Here’s an example of adding a third-party component to your site.
First, you have to install the component or library’s package via a package manager. It’s recommended not to mix package managers, so if you use npm, don’t use another and vice versa.
After you’ve installed a package, import and use it in your page’s source:
Since Gatsby uses Server-Side Rendering (SSR) to generate your site’s pages, the JSX code you write is usually compiled before the browser loads the page. Because of this, certain features are not available at compile time and can cause a build error.
Some components or code reference browser globals such as
localStorage. These objects are not available at build time and can result in a webpack error when compiling:
To learn more about solutions for supporting SSR and client-side libraries, check out the related section on the Porting from Create React App documentation.
Some packages expect
window or another browser global to be defined. These packages will have to be patched.
You can learn how to patch these packages on the Debugging HTML Builds documentation.
Server-side rendering means pages and content are built out by the Node.js server and then sent to a browser ready to go. It’s like your pages are constructed before even being sent to the user. Gatsby is server-side rendered at build time, meaning that the code that gets to your browser has already been run to build pages and content, but this doesn’t mean you can’t still have dynamic pages.
Some React components don’t have server-side rendering support (SSR) out-of-the-box so you might have to add SSR yourself.
Edit this page on GitHub