Let's look at a simple example of adding SEO to a React component using the react-helmet
library. In this example, we'll create a basic React component and set the page title and meta description dynamically. Install the react-helmet
library:
npm install react-helmet
Make a React component and use
react-helmet
to set the title and meta description:// components/MyComponent.js import React from 'react'; import { Helmet } from 'react-helmet'; const MyComponent = () => { return ( <div> <Helmet> <title>My Page Title</title> <meta name="description" content="This is a description of my page." /> </Helmet> <h1>Welcome to My Page</h1> <p>This is the content of my page.</p> </div> ); }; export default MyComponent;
Add this component to your app. For instance, in your main
App.js
file:// App.js import React from 'react'; import MyComponent from './components/MyComponent'; const App = () => { return ( <div> <MyComponent /> </div> ); }; export default App;
When someone visits this page, the created HTML will have the title and meta description set automatically. Search engines will see this information when they look at your site.
<!-- Rendered HTML --> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>My Page Title</title> <meta name="description" content="This is a description of my page." /> <!-- Other meta tags and head elements may be present based on your configuration --> </head> <body> <!-- Your component content --> <div> <h1>Welcome to My Page</h1> <p>This is the content of my page.</p> </div> </body> </html>
This example shows a simple way to use react-helmet
for adding SEO-related details to your React components. Make sure to change the title and meta description for each page in your app based on its content.