Skip to content

Using Puck with React

Simon Yohannes edited this page Jun 30, 2023 · 2 revisions

Puck and React

Puck works great with react in headless mode. In the backoffice, you would use Vue to extend Puck or just plain javascript but on the front end you should use React for your templates and websites in general if working headless. As you can read here, it's possible to return all pages as JSON.

From here, you need to work on getting Components in React that use the Viewmodels returned from Puck. For this, you need a Page Factory Component in React;

` const PageFactory = (props) => { const location = useLocation(); const [path, setPath] = useState(window.location.pathname); const { fetchPage } = props;

//console.log(props.currentPage, "themodel");
useEffect(() => {
    console.log("setting location",location);
    setPath(location.pathname);
}, [location]);

useEffect(() => {
    console.log("fetching",path);
    fetchPage(path);

}, [path, fetchPage]);

const getComponent = () => {

    const urlParams = new URLSearchParams(window.location.search);
    const paramDict = [];
    if (urlParams) {
        for (var pair of urlParams.entries()) {
            paramDict[pair[0]] = pair[1];
        }
    }
    //debugger;
    
    const ViewModelComponent = React.lazy(() => import("./Components/{props.currentPage?.ViewModel?.Type}"));
    return <ViewModelComponent model={props.currentPage} params={paramDict} />

    //alternative
    switch (props.currentPage?.ViewModel?.Type) {
        case "AddBookList":
            return <AddBookList model={props.currentPage} params={paramDict} />
        case "AddBook":
            return <AddBook model={props.currentPage} params={paramDict} />
        default:
            return <Homepage model={props.currentPage} params={paramDict} />
    }
}

return getComponent();

}

const mapStateToProps = (state, ownProps) => {

return { currentPage: state.currentPage };

}

export default connect(mapStateToProps, { fetchPage })(PageFactory);

`

If you study the code above, it's the basic template for lazy loading (or static loading) components (for front end templates) based on Viewmodels returned from Puck. It's the ideal way to work with Puck and React so give it a try.