Now to talk about how to add SEO on a React component using the react-helmet
library. In this example, we'll create a basic React component and dynamically set the page title and meta description.
Install the
react-helmet
library:npm install react-helmet
Create 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;
Integrate this component into your application. For example, 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 a user visits this page, the HTML generated will include the dynamically set title and meta description. When search engines crawl your site, they will find this information:
<!-- 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>
Conclusion:
This example demonstrates a basic usage of react-helmet
to add dynamic SEO-related information to your React components. Remember to customize the title and meta description based on the content of each page within your application.