How to add shopify polaris components with react when using python flask for the server side?

802 Views Asked by At

I am trying to use shopify polaris on my embedded shopify app I started with flask.

I have no issue adding the css polaris components but would like the react version as it seems a lot easier.

My app is authentificating the store via flask with a install and connect routes and including the appbridge in a javascript section inside the html.

It goes like this:

@app.route('/install', methods=['GET'])
def install():
    if request.args.get('shop'):
        shop = request.args.get('shop')
    else:
        return Response(response="Error:parameter shop not found", status=500)

    return render_template("login.html", shop = shop, api_key = cfg.API_KEY,
    scopes = cfg.SHOPIFY_CONFIG["SCOPE"],
       redirect_uri= cfg.SHOPIFY_CONFIG["REDIRECT_URI"])

login.html:

<!doctype html>

<head>
    <title>Logging in...</title>

    <script src="https://unpkg.com/@shopify/[email protected]/umd/index.js"></script>
    <script>
        var AppBridge = window['app-bridge'];
        var Redirect = AppBridge.actions.Redirect;
        const permissionUrl =
            "/oauth/authorize?client_id={{ api_key }}&scope={{ scopes }}&redirect_uri={{ redirect_uri }}";

        if (window.top == window.self) {
            window.location.assign("https://{{ shop }}/admin" + permissionUrl );

        } else {
            const app = AppBridge.createApp({
                apiKey: "{{ api_key }}",
                shopOrigin: "{{ shop }}",
                forceRedirect: true
            });

            Redirect.create(app).dispatch(Redirect.Action.ADMIN_PATH,permissionUrl );
    </script>
</head>

<body>
    
</body>

then the connect route to render my app template:

@app.route('/connect', methods=['GET'])
def connect():
    shop = request.args.get("shop")
    if session.get('shop') != shop:
        session.clear()
    if session.get("access_token") is None:
        params = {
            "client_id": cfg.API_KEY,
            "client_secret": app.secret_key,
            "code": request.args.get("code")
        }
        
        resp = requests.post(
            "https://{0}/admin/oauth/access_token".format(
                request.args.get("shop")
            ),
            data=params
        )

        if 200 == resp.status_code:
            resp_json = json.loads(resp.text)
            session['access_token'] = resp_json.get("access_token")
            session['shop'] = request.args.get("shop")
            session.modified = True
        
        
    return render_template('/index.html', sess = session, api_key = cfg.API_KEY, shop = shop)

Now in my index.html i am trying to use app brigge which seems to work but I am not able to render the react-polaris component.

<!DOCTYPE html>
<html lang= "en">
    <head>
      
        <link
        rel="stylesheet"
        href="https://unpkg.com/@shopify/[email protected]/dist/styles.css"
      />

        <meta charset= "UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="shortcut icon" href="#">
      

        <!-- <link rel= "stylesheet" href='{{ url_for("static", filename = "css/main.css") }}'> -->
        
        <script src="https://unpkg.com/@shopify/[email protected]/umd/index.js"></script>
      

<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>


</head>
<body>
    
    <script>



        var AppBridge = window['app-bridge'];
        
        const app = AppBridge.createApp({
            apiKey: "{{ api_key }}",
            shopOrigin: "{{ shop }}",
            // forceRedirect: true
        });
        </script>

<script>
  
    import React, { Component } from 'react';
    import { render } from 'react-dom';
    
    import {AppProvider, Page, Card, Button} from '@shopify/polaris';
    
    class App extends Component {
      constructor() {
        super();
      }
    
      render() {
        return (
          <AppProvider>
            <Page title="Example app">
              <Card sectioned>
                <Button onClick={() => alert('Button clicked!')}>Example button</Button>
              </Card>
            </Page>
          </AppProvider>
        );
      }
    }
    
    render(<App />, document.getElementById('root'));
    
      </script>
      <div id="root"></div>
</body>
</html>

I added polaris with "yarn add @shopify/polaris" in the console.

I am not sure if what I am trying to achieve is even possible?? Maybe the authentification and the app bridge as to be done in react as well?

Any help would be highly appreciated!! I would very much like to avoid using polaris css and making my own javascript. If there are any ressources for react-polaris combined with python flask it would be awesome!!

Cheers

0

There are 0 best solutions below