I building a small blog app using React and Redux. The blog show Posts page with title, author, tags and description of a post. When clicking on title or "read more" button, I want to load and render an HTML file with corresponding post from a local project's data folder with all the posts.
Redux is managing the state of the blog, loading initial posts.json file with 8 different posts, including htmlPath for the corresponding html file in the data folder.
You can try react-templates. This is 'the' best available. You can have your template as an external file and can load it whenever you want and it'll render like charm with all the React API available.
Hope it helps.
The way I see it is that you have 2 problems to solve here. The first is how to set the
innerHTML
of an element in React. The other is how to get a specific HTML to render depending on a given variable (e.g the current route, the input of a textfield, etc).1. Setting the
innerHTML
of an elementYou can do this with the
dangerouslySetInnerHTML
prop. As the name suggests it sets theinnerHTML
of the said element to whatever you specify... and yes, the "dangerously" is accurate as it's intended to make you think twice before using this feature.The Official Documentation reads as follows:
Check out this Demo or the snippet below.
2. Fetching the HTML from an external source
Note that the above example does not actually get the HTML from an external file, but is entered directly as a string.
One simple way to do dynamically fetch a choose a specific file would be to let your backend (e.g php) read the file from a local folder, parse the text, and send it back through an AJAX request.
Example
While Chris's answer was good, some more digging was required to make it work. Here are the steps that you need to take:
Add html loader to your project:
Add the following rule to your webpack.config file:
Now you can import your html file as follow:
If you really sure, get the post contents to frontend how you like from file system with server code, and show it in React component with
dangerouslySetInnerHTML
:More in docs: https://facebook.github.io/react/tips/dangerously-set-inner-html.html