How to use your Component Library on static HTML pages
by Sam Bernhardt
Note: this was an experimental project that's a workaround to refactoring some static HTML pages that are part of KickUp's product. The ideal solution would be to rebuild the static HTML pages as React apps so we can directly use our reusable componentLibrary, but this proposes a clever workaround to achieve consistent components and styles without that migration.
Instead of ReactDOM.render() rendering a single <App/> component, index.js renders a component inside each element that has a data‑component attribute.
Before rendering though, it passes the contents of the original element to the <Button/> component using a children prop.
The <Button/> component can be defined like any other React component, but uses the dangerouslySetInnerHTML prop to set the component's children as the innerHTML string from the original element:
import React from 'react';
import styled from 'styled-components';
const Button = styled.div`
padding: 12px 16px;
border-radius: 4px;
background: black;
color: white;
cursor: pointer;
`;
export default ({ children }) => (
<Button
dangerouslySetInnerHTML={{ __html: children }}
/>
)
And that's the basic concept. 🎉
The bundled React index.js file can be used in any non-React context, replacing standard HTML elements with React components.
This method works best for UI primitives like labels or buttons. However, as long as index.js knows what component to replace the specified element with, this method could theoretically work for any component.
Enter your name
Submit
Props
Props could be automatically passed by prepending the prop name with data- and specifying it on the original element.