How to create a page with URL in React

Viewed 1464

The application is receiving from the server an HTML file.

This data (responseToPost) can be shown on the page like this:

<div dangerouslySetInnerHTML={{ __html: this.state.responseToPost }} />

I was wondering if it's possible to create a new URL where to show this data?

The html file has this format:

<hr />
<p>title: "my-title"</p>
<h2 id="123">a....

and I want that the created page to be like: localhost:3000/my-title and show the HTML on that page.

Is it something possible? What approach should I use?

2 Answers

This is perfectly doable with React Router.

You'll need to pull in the npm dependency to your project, then you can set up your route, my-title as a <Route>, then render whatever you like on that page, in your case responseToPost.

Obviously setup requires a few more steps than just declare a <Route> but the official documentation is very good: React Router official doc

You can use React Router for that. I would suggest having a special route for it, let's say /pages/ (code simplified):


// On your Routes (usually App.js) page:
import { BrowserRouter as Router, Route } from "react-router-dom";

<Router>
  <Route path="/pages/:pageslug" component={Page} />
</Router>

const PAGES = {
  'my-title': "<div>...</div>"
};

// Page.js
export function Page({ match }) {
  return (
    <div dangerouslySetInnerHTML={{ __html: PAGES[match.params.pageslug] }} />  
  );
}
Related