I'm building a react SPA with Wordpress running as the backend, but it's not headless, so the entire frontend is included in the theme. I simply run npm build and enqueue the production files in the functions.php file. The application is rendered into a <div id="root"></div> inside a template file. My wordpress install is set to have a static homepage, which uses the template that contains the React root div.
This seems to work just fine, apart from the Router. If I go to a different address, say https://mywebsite/about, it tries to load a wordpress page named about, rather than staying on the same page, and using the router to render the appropriate component. Is there something setting I have to change in the .htaccess file? Or is there something else I am missing?
If you have a React app on your WP page and you don't want to edit .htaccess you can also add rewrite rules with add_rewrite_rule() in functions.php to redirect all requests to your react app WP page to be handled by React Router.
add_action('init', 'wp55290310_rewrite_rules');
function wp55290310_rewrite_rules() {
add_rewrite_rule('^your-react-app-root/(.+)?', 'index.php?pagename=your-react-page-name', 'top');
}
You need to specify the baseName in React Router:
<BrowserRouter basename="/your-react-app-root">
<Switch>
<Route exact path="/" component={SomeComponent} />
<Route exact path="/other-page" component={OtherComponent} />
</Switch>
</BrowserRouter>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With