Bundling React
Like most libraries, it suffices to just install the React libraries with NPM and import them into your TypeScript code. Webpack will take care of bundling the library code. The only slightly trickier thing with React is that you need to configure your plugin to support JSX syntax.
Here's how to enable JSX syntax in the sample Webpack project above (assuming you've already followed the steps in the Bundling with Webpack section.
Full sample code for this tutorial is available in the Figma Plugin Samples repository.
1. Install the relevant React packages
npm install react react-dom
npm install --save-dev @types/react @types/react-dom
tsconfig.json
to support parsing JSX syntax:
2. Modify JSX is an extension of the JavaScript syntax that allows you to write HTML-like tags inside the JavaScript.
{
"compilerOptions": {
...
"jsx": "react"
}
}
src/ui.html
3. Update This just creates an empty <div>
. On startup, React will take this <div>
and replace it with what it renders.
<div id="react-page"></div>
src/ui.ts
to src/ui.tsx
4. Update import * as React from 'react'
import * as ReactDOM from 'react-dom'
import './ui.css'
declare function require(path: string): any
class App extends React.Component {
textbox: HTMLInputElement
countRef = (element: HTMLInputElement) => {
if (element) element.value = '5'
this.textbox = element
}
onCreate = () => {
const count = parseInt(this.textbox.value, 10)
parent.postMessage({ pluginMessage: { type: 'create-rectangles', count } }, '*')
}
onCancel = () => {
parent.postMessage({ pluginMessage: { type: 'cancel' } }, '*')
}
render() {
return <div>
<img src={require('./logo.svg')} />
<h2>Rectangle Creator</h2>
<p>Count: <input ref={this.countRef} /></p>
<button id="create" onClick={this.onCreate}>Create</button>
<button onClick={this.onCancel}>Cancel</button>
</div>
}
}
ReactDOM.render(<App />, document.getElementById('react-page'))
Note how, on the last line, we refer to the <div id="react-page">
that we created previously.
ui.tsx
entry point in webpack.config.js
:
5. Refer to the new {
...
"ui": "./src/ui.tsx", // The entry point for your UI code
...
}
6. Re-run the Webpack bundler on the command line
npx webpack --mode=production
That's it!