This project's public API token: APITOKEN
Overview
This covers integrating Plasmic into your existing React codebase.
Want to quickly generate a new codebase with Plasmic already integrated? Use create-plasmic-app instead, or just press the Publish button in your project to push a new repo to GitHub!
Want to generate source code into your codebase (warning: advanced)? Learn about codegen.
Note that the plain React docs assume a single-page application with client-side rendering, and not server-side rendering or static rendering. Unlike with metaframeworks such as Next.js, how this is done is different for different environments—even the routing system can vary. If you’d like help more direct help integrating in your stack, please get in touch.
Installation
npm install @plasmicapp/loader-react# or yarn add @plasmicapp/loader-react
Initialization
Initialize Plasmic with the project ID and public API token. Define this in its own module to make it available globally.
import { initPlasmicLoader } from "@plasmicapp/loader-react";export const PLASMIC = initPlasmicLoader({projects: [{id: "PROJECTID", // ID of a project you are usingtoken: "APITOKEN" // API token for that project}],// Fetches the latest revisions, whether or not they were unpublished!// Disable for production to ensure you render only published changes.preview: true,})
To find your project’s ID and public API token: open the project in Plasmic Studio.
The project ID is in the URL, like: https://studio.plasmic.app/projects/PROJECTID
.
The public API token can be found by clicking the Code toolbar button.
Auto load all Plasmic pages
To automatically render all Plasmic-defined pages at the routes specified in Plasmic, create a catch-all route for your specific routing framework.
Here is an example for react-router, both v5 and v6:
import {initPlasmicLoader,PlasmicRootProvider,PageParamsProvider,PlasmicComponent,ComponentRenderData} from '@plasmicapp/loader-react';import { BrowserRouter as Router, Routes, Route, Link, useLocation, useSearchParams } from 'react-router-dom';import { useEffect, useState } from 'react';import { PLASMIC } from './plasmic-init';function AppRoot() {return (<PlasmicRootProvider loader={PLASMIC}><Router><Routes><Route path="/" element={CatchAllPage()} /></Routes></Router></PlasmicRootProvider>);}// We try loading the Plasmic page for the current route.// If it doesn't exist, then return "Not found."export function CatchAllPage() {const [loading, setLoading] = useState(true);const [pageData, setPageData] = useState<ComponentRenderData | null>(null);const location = useLocation();const searchParams = useSearchParams();useEffect(() => {async function load() {const pageData = await PLASMIC.maybeFetchComponentData(location.pathname);setPageData(pageData);setLoading(false);}load();}, []);if (loading) {return <div>Loading...</div>;}if (!pageData) {return <div>Not found</div>;}// The page will already be cached from the `load` call above.return (<PageParamsProviderroute={location.pathname}query={Object.fromEntries(searchParams)}><PlasmicComponent component={location.pathname} /></PageParamsProvider>);}
Render a single Plasmic page or component
Note: You can instead auto-load all Plasmic pages at the correct routes (recommended) rather than manually loading individual pages—see previous section.
For client-rendered or single-page apps, we fetch components dynamically at runtime. (These are cached for the lifetime of the application.) These are served from a globally replicated instance of the AWS Cloudfront CDN.
Add <PlasmicRootProvider/>
somewhere close to the root of your app,
then drop in a <PlasmicComponent/>
anywhere to render the actual component.
The following is an example.
COMPONENT_OR_PAGEROUTE
refers to the name of the page or component that you want to render, such as Winter22LandingPage
.
If it’s a page, you can also use the route you assigned the page in Plasmic, like /landing
.
import { PlasmicRootProvider, PlasmicComponent } from '@plasmicapp/loader-react';import { PLASMIC } from '../plasmic-init';export function MyComponent() {return (<PlasmicRootProvider loader={PLASMIC}><PlasmicComponent component="COMPONENTNAME" /></PlasmicRootProvider>);}
Adding custom code components
Let your Plasmic Studio users drag/drop and visually manipulate your own custom React components! Learn more.
Step 1
Create a simple example React component:
import * as React from 'react';export interface HelloWorldProps {children?: React.ReactNode;className?: string;verbose?: boolean;}export function HelloWorld({ children, className, verbose }: HelloWorldProps) {return (<div className={className} style={{ padding: '20px' }}><p>Hello there! {verbose && 'Really nice to meet you!'}</p><div>{children}</div></div>);}
Step 2
Add the following to your src/plasmic-init.ts
to register it:
import { HelloWorld } from './components/HelloWorld';// ...export const PLASMIC = initPlasmicLoader(/* ... */);PLASMIC.registerComponent(HelloWorld, {name: 'HelloWorld',props: {verbose: 'boolean',children: 'slot'}});
Step 3
Create a host page at route /plasmic-host
:
import * as React from 'react';import { PlasmicCanvasHost } from '@plasmicapp/loader-react';import { BrowserRouter, Route, Routes } from 'react-router-dom';import { PLASMIC } from './plasmic-init';export default function AppRoot() {return (<BrowserRouter><Routes>{/* Your other routes... */}<Route path="/plasmic-host" element={<PlasmicCanvasHost />} /></Routes></BrowserRouter>);}
Step 4
Start your app:
npm run start
And check that you see a confirmation message at http://localhost:{props.port}/plasmic-host.
Step 5
Open https://studio.plasmic.app, click the menu for the current project, select “Configure project,” and set it to http://localhost:{props.port}/plasmic-host.
Step 6
Re-open this project (or reload this tab) to see your component listed in the insert menu!
Later, after you deploy the route to production, update the project to use your production host URL instead,
such as https://my-app.com/plasmic-host
.
This way, other members of your team
(who can’t access your localhost dev server) will be able to open and edit the project in
Plasmic.
(Again, the /plasmic-host route itself is a special hidden route not meant for humans to visit; it is only for Plasmic Studio to hook into.)
There’s much more to explore!
For example:
- Explore what you can do with code components.
- Render different variants of your pages/components.
- Override the content or props in your design.
- Add hooks for state and behavior to any component.
- (Advanced) Use Plasmic as a UI builder for developers.
Continue learning in the full docs.