React is a popular JavaScript library for building user interfaces, known for its efficiency and flexibility. While React primarily deals with creating components that manage their own state, there are instances where you might need to render HTML content dynamically, especially when dealing with data from an API or when you need to display user-generated content.
In this tutorial, we’ll explore how to render HTML content, including a title, in a React component. We’ll go through a step-by-step example to demonstrate how to achieve this.
Prerequisites
Before we begin, make sure you have Node.js and npm (Node Package Manager) installed on your machine. You’ll also need a basic understanding of React and JSX.
Step 1: Set Up Your React Project
If you haven’t already, create a new React project using Create React App. Open your terminal and run the following command:
npx create-react-app render-html-example
This command will create a new directory called render-html-example
with a basic React project structure.
Step 2: Create a New Component
Inside the src
directory of your project, create a new file called HTMLRenderer.js
. This file will contain the component responsible for rendering HTML content.
// HTMLRenderer.js
import React from 'react';
const HTMLRenderer = ({ title, htmlContent }) => {
return (
<div>
<h1>{title}</h1>
<div dangerouslySetInnerHTML={{ __html: htmlContent }} />
</div>
);
};
export default HTMLRenderer;
In this component, we accept two props: title
and htmlContent
. We render the title inside an <h1>
tag and use dangerouslySetInnerHTML
to render the HTML content safely. Using dangerouslySetInnerHTML
bypasses React’s escaping and allows you to inject HTML directly into the DOM, but be cautious when using it to prevent cross-site scripting (XSS) attacks.
Step 3: Use the Component
Now, let’s use the HTMLRenderer
component in our App.js
file to see it in action.
// App.js
import React from 'react';
import HTMLRenderer from './HTMLRenderer';
function App() {
const title = 'Sample HTML Page';
const htmlContent = '<p>This is a paragraph.</p><p>This is another paragraph.</p>';
return (
<div className="App">
<HTMLRenderer title={title} htmlContent={htmlContent} />
</div>
);
}
export default App;
Step 4: Run Your React App
Save all your files and start the development server by running:
npm start
Open your browser and navigate to http://localhost:3000
to see your React app running. You should see the title “Sample HTML Page” followed by the HTML content rendered by the HTMLRenderer
component.
Conclusion
In this tutorial, you learned how to render HTML content, including a title, in a React component. By using the dangerouslySetInnerHTML
attribute, you can safely render HTML content within your React application. However, remember to sanitize user-generated content to prevent security vulnerabilities.
Feel free to experiment further by fetching HTML content from an API or integrating this approach into your existing React projects!