think-serious
think-serious

Reputation: 1319

How to integrate React app into Wordpress (react router)?

I've created a react app to embed to wordpress site. React app is created by create-react-app and after bundling, I've uploaded it to wordpress site. Then created a page to load the bundled js file. (following this guide https://medium.com/@CodeCareerCoach/react-app-inside-a-wordpress-page-or-post-4c7d38181b3d)

So it shows the react app and works for the base route.

When I navigate, it still works, when I refresh I get 404 ERR.

This is the routing of react app.

  return <BrowserRouter basename='/testweb'>
    <Layout menuItems={menuItems} pages={pages}>
      <Switch>
          <Route exact path="/" render={() => <div>okay</div>} />
          <Route exact path="/home" render={(props) => {
              return <div>asdf</div>
            }} 
          />
...
          <Route render={(props)=> props.location.pathname } />
      </Switch>
    </Layout>
  </BrowserRouter>

in package.json, I've set homepage to /testweb How can I get the nested routes working?

Upvotes: 1

Views: 2151

Answers (1)

think-serious
think-serious

Reputation: 1319

I found my own answer. Please share a better one if you have.

Let's say our app's name is testweb.

  • First, changed homepage attribute in package.json to another,
    testweb-react.
  • Kept the routing as it is(using testweb as base url).
  • Uploaded build files to root of wordpress site.

  • Created /testweb/.htaccess file to internally redirect to testweb-react

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ – [L]
RewriteRule ^ /testweb-react/ [L]
</IfModule>

Hope this helps others also!

Upvotes: 1

Related Questions