I am building a WordPress plugin using react and I'm using react on the WordPress frontend. When I change route using react and reload the page then I'm getting the 404 error
Here is my webpack.config.js
file
const path = require('path');
const defaultConfig = require('@wordpress/scripts/config/webpack.config');
const ReactJs = {
...defaultConfig,
entry: {
'index': './src/index.js',
},
output: {
path: path.resolve(__dirname, 'build/'),
filename: '[name].js'
}
}
module.exports = [ReactJs];
I want the solution within my plugin directory. Not in the .htaccess file
I found the solution on my own. Here is the solution.
I load react on a page whose slug is frontend-dashboard
. So I add a basename in BrowserRouter
ReactDOM.render(
<React.StrictMode>
<BrowserRouter basename='/frontend-dashboard/'>
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById("frontend-dashboard")
);
And after that, I create a custom endpoint for my WordPress plugin.
add_action( 'init', 'tf_add_rewrite_endpoint' );
function tf_add_rewrite_endpoint() {
add_rewrite_endpoint( 'hotels', EP_ROOT | EP_PAGES );
add_rewrite_endpoint( 'add-new-hotel', EP_ROOT | EP_PAGES );
}
Once I registered the new endpoint, I checked the newly registered endpoint in the current URL. If it matched, I am setting the template path to frontend-dashboard.php where actually react loaded by this id frontend-dashboard
add_filter( 'template_include', 'tf_template_include' );
function tf_template_include( $template ) {
$page_slug = array('hotels', 'add-new-hotel');
if ( is_page() && in_array( get_query_var( 'pagename' ), $page_slug ) ) {
$template = TF_TEMPLATE_PATH . 'page-templates/frontend-dashboard.php';
}
return $template;
}