Search code examples
javascriptreactjsreact-sketchapp

Creating universal React components


We're trying to create a common UI component library for both our designers and developers with React. In other words - we want to render our component library to both react-dom and react-sketchapp.

We would love to specify the structure once, the styles once and the behavior once.

We can get there (kind of at least) with projects like react-primitives or styled-components/primitives, but this approach basically stops us from having any semantics in our HTML. When all you have to work with is Text, you can't really specify whether that text is a <p> or an <h1>.

How have people dealt with sharing code this way previously? How can we basically render HTML (via JSX) to Sketch?


Solution

  • You can create your own primitives by creating multiple files targeting different platforms.

    For example, if you would like to create a primitive for h1, you would create a file called h1.web.js

    const H1 = (props) => <h1 {...props} />
    

    and a file called h1.sketch.js

    const H1 = (props) => <Text {...props} />
    

    (and maybe specify a default style to match what you can find on the web).

    When you const H1 = require('./h1'), skpm will pick up h1.sketch.js automatically. You then have to modify your webpack (or whichever bundler you are using) configuration to pick up h1.web.js in priority.