Search code examples
javascriptreactjswagtailweb-frontendwagtail-apiv2

How to integrate ReactJS application with Wagtail API. Steps to follow?


I am trying the write application in ReactJS and backend will be using Wagtail API. I am trying to find out what all steps/what all configuration needs to be done on front end side as well on backend to integrate ReactJS with the Wagtail?


Solution

  • It doesn't matter which backend you are using. You just need to call the services from your API in the React.

    Small example:

    File index.js

    import React from 'react';
    import ReactDOM from 'react-dom';
    import App from "./App";
    
    export class ReactApp {
        static renderService(props, element) {
            ReactDOM.render(<App {...props}/>, element);
        }
    }
    
    window.ReactApp = ReactApp;
    

    File App.js

    import React from 'react';
    
    class App extends React.PureComponent {
    
        constructor(props) {
            super(props);
    
            this.state = {
                data: null,
                inProgress: false
            }
        }
    
        async fetchData(url) {
            return await fetch(url)
                .then((response) => response.json())
                .then(data => this.setState({data}))
                .finally((e) => {
                    this.setState({inProgress: false})
                });
        }
    
        componentDidMount() {
            this.fetchData(this.props.url);
        }
    
    
        render() {
            const {data, inProgress} = this.state;
    
            return (
                <div className="app">
                    {
                        !inProgress && data &&
                        (
                            <div className="app__list">
                                {
                                    data.map(item => <span className="app__list-item">{item.title}</span>)
                                }
                            </div>
                        )
                    }
                </div>
    
            );
        }
    }
    
    export default App;
    

    Then build your js code with webpack with index.js entry point and call it in your html

    <div id="app"></div>
    <script  type="text/javascript" src="build.js"></script>
    <script>
        ReactApp. renderService({url: 'https://yourApiUrl'}, document.getElementById('app'));
    </script>