Engage Users Instantly: Embed an Interactive Demo in your React SPA
If a picture is worth a thousand words, then an interactive demo must be worth... a million?
Do you enjoy scrolling through buzzwords to understand an app's purpose? Probably not. And I didn't care to write all that blather for my latest passion project, Wanna. So I pursued a more interesting solution: nest my app inside its own landing page for users to explore!
Implementation
Thanks to React's composability, we can almost simply render our root App component and call it a day:
export const InteractiveDemo = () => { return ( <App /> ) }
However, you'll run into a few problems:
- The demo app's navigation will navigate the real app
- The demo app will retrieve real data, which may fail or not showcase it well
- It may not be obvious to users what they're looking at
Let's solve those. Wanna uses React Router v6 and Apollo GraphQL, but the concepts apply regardless of technology.
Navigation
To separate the demo app's navigation from the real app, we wrap it inside another navigation provider:
+import { MemoryRouter, UNSAFE_LocationContext } from 'react-router' export const InteractiveDemo = () => { return ( + // Hack to nest MemoryRouter inside BrowserRouter. + // https://github.com/remix-run/react-router/issues/7375 + <UNSAFE_LocationContext.Provider value={null}> + <MemoryRouter initialEntries={['/app']}> <App /> + </MemoryRouter> + </UNSAFE_LocationContext.Provider> ) }
Note we use a MemoryRouter so the browser remains on the same page while the demo navigates internally.
Data
To provide the demo app with fake data, we maintain a fake "backend" inside the client app with useState and serve it via a mock client or server (depending on implementation). It's minimally invasive to the rest of the app code, and even lets us use the demo for manual testing - very handy when iterating quickly.
I used mock-apollo-client; for REST or tRPC, you might use something like nock. They're meant for automated testing but are exactly what we need here.
First, we create a mock client whose request handlers query and mutate demo data in a way that mimicks the real backend:
import { InMemoryCache } from '@apollo/client' import { createMockClient, createMockSubscription } from 'mock-apollo-client' import { useMemo, useState } from 'react' // GraphQL documents that our client sends to the real server import GET_FRIENDS from '../../gql/getFriends.gql' import ADD_FRIEND from '../../gql/addFriend.gql' // Simplified example export const useDemoClient = () => { const [friends, setFriends] = useState[{ __typename: 'User', id: 1, name: 'Nick', }] // Cache should persist across clients const cache = useMemo(() => { // Should be the same cache configuration you provide to your real Apollo client return new InMemoryCache() }, []) // We need to recreate the mock client whenever the data changes // because it doesn't support resetting request handlers. const mockClient = useMemo(() => { const client = createMockClient({ cache }) client.setRequestHandler(GET_FRIENDS, () => Promise.resolve({ data: { friends: friends } })) client.setRequestHandler(ADD_FRIEND, ({ user }) => { setFriends((prev) => prev.concat([user])) return Promise.resolve({ data: { addFriend: user } }) }) return client }, [friends]) return mockClient }
Then just like we did with navigation, we wrap our demo in a new provider with our mock client:
+import { ApolloProvider } from '@apollo/client' export const InteractiveDemo = () => { + const demoClient = useDemoClient() return ( + <ApolloProvider client={demoClient}> <UNSAFE_LocationContext.Provider value={null}> <MemoryRouter initialEntries={['/app']}> <App /> </MemoryRouter> </UNSAFE_LocationContext.Provider> + </ApolloProvider> ) }
If you used a mock server instead, you'd inject its URL into the demo app's real client.
Visuals
It works! Now how do we make it obvious to the user that they're viewing an interactive demo?
Wanna is mobile-first, so I chose to render the demo inside a phone frame. I used devices.css because it offers the devices I thought looked best (i.e. minimal bezel to maximize demo space). But for simplicity, here we'll use a library that supports React out-of-the-box: react-device-frameset.
Let's also use zoom to shrink the demo UI and nicely nest it inside the rest of the page. In Wanna I had to invert and account for this zoom when using
export const InteractiveDemo = () => { return ( <App /> ) }
The above is the detailed content of Engage Users Instantly: Embed an Interactive Demo in your React SPA. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.
