Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk11 min

How to Embed a React Application in WordPress

Embed React in WordPress by rendering a mount element, enqueueing the production bundle and stylesheet through a plugin or theme, and connecting data through the REST API. This guide covers islands, headless builds, iframes, security and troubleshooting.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The dependable way to embed an existing React application in WordPress is to let WordPress render a mount element, then enqueue the React production bundle and stylesheet through a theme or plugin. React takes over only that element, while WordPress continues to control the page template, navigation, editor workflow and SEO markup. For a separate, fully React-owned site, use WordPress as a REST API instead. An iframe is appropriate only when you deliberately want a strongly isolated product.

Choose the right integration boundary

“Embed a React app” can describe three different architectures. Decide which one you need before moving files or writing PHP, because the choice determines routing, SEO, authentication, deployment and the amount of WordPress integration you must maintain.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Architecture Best when What WordPress owns Main trade-off
React island in a theme or plugin One tool, dashboard, calculator or interactive area belongs inside normal WordPress pages Document structure, templates, menus, editor placement and most SEO output You must load assets only where needed and isolate React CSS from the active theme
Headless or separately hosted React frontend React should own routing and nearly the entire visitor experience Content and administration through the WordPress API Separate hosting, preview, caching, authentication, CORS and deployment coordination
Iframe or external embed The application is maintained as a completely separate product and visual inclusion is the only requirement Only the surrounding page Weakest integration with WordPress navigation, styling, accessibility, analytics and shared state

For most existing WordPress sites, start with a React island. It keeps the page server-rendered and gives editors a shortcode or block they can place on selected pages. Choose headless only when React genuinely needs to own the whole page and its URL routing. Choose an iframe when isolation matters more than integration.

What you need before you start

  • A working React project that can produce a production build.
  • Access to a WordPress child theme or a custom plugin. A plugin is usually safer when the application is a reusable feature that should survive theme changes.
  • A way to copy the build output (JavaScript, CSS and any assets) into that plugin, theme or an approved asset host.
  • A page, template, shortcode or block location where WordPress can print one unique mount element.
  • Permission to register scripts and, if the app writes data, permission to create or use authenticated REST endpoints.

Development-server URLs are not a production integration. Build the app for production first, then deploy the generated files at stable URLs that WordPress can enqueue.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Build the React application for production

Use the production command defined by your project (commonly npm run build). The output should contain a browser-ready JavaScript bundle and, when your setup extracts styles, one or more CSS files. Copy those files into a predictable directory such as my-react-app/assets/ inside a plugin.

Keep the application entry point focused on a root element supplied by WordPress. A minimal entry file looks like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { createRoot } from 'react-dom/client';
import App from './App';
import './app.css';

const mount = document.getElementById('my-react-app');

if (mount) {
  createRoot(mount).render(<App />);
}

The guard matters: the bundle may be present in a browser where the mount element is absent because of caching, a template change or an accidental global enqueue. Without it, React will throw while trying to mount.

If the build tool emits hashed filenames, either copy a manifest and resolve the current names in PHP or configure stable output names. A WordPress enqueue must point to the files that actually exist after deployment.

Render a mount point from WordPress

WordPress must output an element before the React bundle runs. A shortcode is a practical boundary when editors should choose which pages contain the app:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
function my_react_app_shortcode($atts = array()) {
    $atts = shortcode_atts(
        array('class' => ''),
        $atts,
        'my_react_app'
    );

    $class = 'my-react-app-root ' . sanitize_html_class($atts['class']);

    return '<div id="my-react-app" class="' . esc_attr(trim($class)) . '"></div>';
}
add_shortcode('my_react_app', 'my_react_app_shortcode');

An editor can then place [my_react_app] in the selected page. Keep the ID unique. If a template can contain more than one instance, use a class and generate a separate root for each instance instead of creating duplicate IDs; the simple example above is intended for one app per page.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A block render callback, a page-template file or a controlled theme component can output the same mount element. Blocks are preferable when editors need a structured configuration UI; a template is preferable when the app belongs to one fixed layout.

Enqueue the bundle and stylesheet correctly

wp_enqueue_script() is WordPress’s recommended mechanism for adding JavaScript. It registers or enqueues a script with a unique handle, source URL, dependencies, version and loading arguments. Front-end files belong on wp_enqueue_scripts; dashboard files belong on admin_enqueue_scripts.

The following plugin example loads the files only on singular posts or pages that contain the shortcode. It uses plugins_url() rather than a hardcoded domain and uses the file modification time as a cache-busting version.

<?php
function my_react_app_enqueue_assets() {
    if (!is_singular()) {
        return;
    }

    global $post;
    if (!$post || !has_shortcode($post->post_content, 'my_react_app')) {
        return;
    }

    $base_path = plugin_dir_path(__FILE__) . 'assets/';
    $base_url  = plugins_url('assets/', __FILE__);
    $script    = $base_path . 'index.js';
    $style     = $base_path . 'index.css';
    $version   = file_exists($script) ? filemtime($script) : null;

    wp_enqueue_style(
        'my-react-app',
        $base_url . 'index.css',
        array(),
        file_exists($style) ? filemtime($style) : null
    );

    wp_enqueue_script(
        'my-react-app',
        $base_url . 'index.js',
        array(),
        $version,
        array(
            'in_footer' => true,
            'strategy'  => 'defer',
        )
    );
}
add_action('wp_enqueue_scripts', 'my_react_app_enqueue_assets');

The defer strategy allows the browser to download without blocking HTML parsing while preserving execution order relative to eligible dependencies. If your bundle depends on another script, list that dependency by its WordPress handle and verify the resulting order. Do not add async merely to make a page appear faster when execution order matters.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

If the app is rendered by a block or template rather than a shortcode, replace the has_shortcode() test with a condition that reliably identifies those pages. The principle is the same: do not ship a large application bundle site-wide when only one route needs it.

For a dashboard page, use the same enqueue pattern from admin_enqueue_scripts and check the current screen before loading the files. Front-end and admin hooks are not interchangeable.

Keep React CSS from changing the theme

Enqueue the generated stylesheet through WordPress’s style API and scope selectors beneath a root class. For example:

.my-react-app-root {
  color: #202124;
  font-family: system-ui, sans-serif;
}

.my-react-app-root .button {
  border: 0;
  border-radius: 0.4rem;
  padding: 0.6rem 0.9rem;
}

.my-react-app-root h2 {
  margin-block: 0 1rem;
}

Scoping prevents generic selectors such as button, h2 or input from restyling unrelated theme content. Conversely, inspect the active theme for global rules that may override your component styles. Prefer component classes over broad element selectors, and test focus states, form controls, spacing and responsive behavior at the breakpoints the site actually uses.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Connect the app to WordPress data

The WordPress REST API exposes JSON resources through predictable, resource-oriented URLs and HTTP verbs. Public posts, pages and other registered content can be fetched directly from the browser. A React component might request posts like this:

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
import { useEffect, useState } from 'react';

export default function PostList() {
  const [posts, setPosts] = useState([]);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('/wp-json/wp/v2/posts?per_page=10')
      .then((response) => {
        if (!response.ok) throw new Error('Request failed');
        return response.json();
      })
      .then(setPosts)
      .catch(setError);
  }, []);

  if (error) return <p role="alert">Unable to load posts.</p>;
  return (
    <ul>
      {posts.map((post) => (
        <li key={post.id}>
          <a href={post.link}>{post.title.rendered}</a>
        </li>
      ))}
    </ul>
  );
}

Use the site-relative path when the React island is served from the same WordPress origin. A separately hosted headless frontend needs the complete site origin and a deliberate CORS policy. Do not assume that every content type is public: custom post types, fields and routes may have different visibility rules.

When a custom endpoint is better

Create a custom REST route when the app needs a purpose-built response rather than several unrelated requests. Return only the fields the interface needs, validate query arguments, and enforce a permission callback for private or mutating operations. Keep server-side authorization authoritative; hiding a button in React is not access control.

Authenticated reads and writes

Anything delivered to a browser should be treated as observable by the user. Never place an application secret in the bundle. For writes, use WordPress authentication and a nonce or another documented authentication method, then validate, sanitize and authorize every request on the server. Handle expired sessions and permission failures as normal UI states instead of assuming every request succeeds.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If you use the WordPress REST API JavaScript client, WordPress documentation identifies wp-api as the relevant script dependency. Enqueue that dependency by its registered handle rather than copying an untracked library into the app.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use a headless React frontend only when it fits

In a headless setup, React renders the complete page and WordPress acts as a content backend. This can provide one routing and component system, but it transfers several responsibilities away from WordPress:

  • Define how preview and draft content reach the frontend.
  • Configure CORS and authentication for the frontend origin.
  • Decide where page metadata, canonical URLs, sitemaps and structured data are generated.
  • Coordinate cache invalidation when editors publish or update content.
  • Provide a deployment pipeline for the React host as well as the WordPress site.

If the requirement is only an interactive calculator or account tool inside two WordPress pages, headless architecture adds complexity without solving a real problem. Keep the island boundary instead.

When an iframe is the least-wrong option

An iframe isolates JavaScript, CSS and release cycles. That is useful when another team owns the application, when its dependencies conflict with the site, or when the product must remain independently deployable. The isolation also means the app does not naturally share WordPress navigation, theme styles, focus management, analytics context or application state.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Give the iframe a meaningful title, define a responsive height strategy, and test keyboard navigation and mobile scrolling. Use an iframe only when those integration costs are acceptable; it should not be the default substitute for a properly enqueued React island.

Make the enqueue conditional and cache-safe

  • Load the bundle only on pages that render its mount point.
  • Use a unique script handle so WordPress can deduplicate it and resolve dependencies.
  • Change the version when a production build changes. A file modification time is a convenient automatic version; a release identifier also works.
  • Confirm that the generated JavaScript and CSS URLs use the production site’s protocol and path.
  • If a CDN or caching layer serves old files, purge or invalidate it after deployment.
  • Do not rely on a development server or localhost URL in a published page.

Conditional loading is both a performance and reliability measure: fewer pages can encounter bundle conflicts, and visitors who never use the app do not download it.

Test the WordPress–React boundary

  1. Open the page source or browser developer tools and verify that WordPress prints exactly one mount element where expected.
  2. Check the Network panel for the JavaScript and CSS files. A 404 usually means the build output was copied to a different directory than the URL in PHP.
  3. Look for a JavaScript syntax or module error. This often indicates that a development build, an incompatible output format or an incomplete asset copy was deployed.
  4. Check dependency order. A script that runs before a library it needs can fail even though both files return HTTP 200.
  5. Inspect the computed styles inside the root and outside it. Unexpected site-wide changes usually come from unscoped selectors; missing styles often come from a stylesheet URL or specificity conflict.
  6. Exercise the REST requests while logged out and logged in. Confirm that public reads do not expose private fields and that unauthorized writes fail.
  7. Test a cached repeat visit after changing the build. If old behavior remains, verify the enqueue version and every intermediate cache.
  8. Test keyboard focus, reduced-motion preferences, narrow screens and screen-reader labels. A React component still has to meet the surrounding page’s accessibility expectations.

Common failure modes and fixes

Symptom Likely cause Fix
Blank area with no visible error The mount ID differs between PHP and React, or the bundle never loaded Match the ID exactly and inspect the browser console and Network panel
“Cannot find element” or a null-root error The bundle is loaded on a page without the mount point Guard the React mount and make the WordPress enqueue conditional
Styles affect the entire site Global selectors in the app stylesheet Scope rules beneath the app root and narrow component selectors
REST request returns 401 or 403 Missing, expired or invalid authentication, nonce or server permission Send the documented credentials or nonce and review the endpoint permission callback
Old interface remains after deployment Browser, plugin, CDN or page cache still serves the previous bundle Change the script version and purge relevant caches
Works in development but not production Absolute development URLs, missing copied assets or a different base path Inspect the production build’s URLs and test the deployed files directly
React appears before required code Incorrect dependency declaration or an overly aggressive loading strategy Declare WordPress script handles as dependencies and verify deferred execution order

Shortcode, block or template: which mount method should you use?

Mount method Choose it when Important consideration
Shortcode Editors need to place one app in post or page content quickly Detect the shortcode before enqueueing and validate any attributes
Dynamic block Editors need a toolbar, inspector controls or structured settings Use the block’s render path to output the mount element and identify pages for asset loading
Page template or theme component The app belongs to a fixed route or layout Keep the element in the template and enqueue only on that template’s pages

All three methods use the same React entry point and WordPress enqueue API. The difference is who controls placement and how reliably you can determine where assets are needed.

Production deployment checklist

  • Build the React project in production mode and copy every emitted JavaScript, CSS and referenced asset file.
  • Place the files in the plugin, child theme or approved asset host that your PHP URL helper addresses.
  • Deploy the PHP that registers the mount output, enqueue callback and any REST routes.
  • Verify front-end hooks on the public page and, separately, admin hooks for dashboard screens.
  • Confirm the bundle’s version changes with each release and that caches can be invalidated.
  • Review permissions for custom routes and test both anonymous and authenticated requests.
  • Check SEO-critical content: a React island should not replace server-rendered headings, links or metadata that search engines and assistive technologies need unless you have deliberately chosen a headless rendering strategy.

Recommended decision

For an existing WordPress site, implement a React island first: output one controlled mount element, enqueue the production assets from wp_enqueue_scripts, scope the CSS, and use the REST API for data. Move to a headless frontend only when React must own routing and the full page lifecycle. Reserve an iframe for deliberate isolation. This boundary keeps WordPress’s editor and SEO strengths while giving the React application a predictable place to run.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.