Importing alpaca into React.js

466 views Asked by At

I am trying to use an Alpaca form within a React app:

import React, { useEffect, useRef } from "react";
import $ from "jquery";
import * as popper from "popper.js";
import * as bootstrap from "bootstrap";
import * as handlebars from "handlebars";
import alpaca from "alpaca";

var jp = require('jsonpath');

export default function Form() {
    useEffect(() => {
        $("#form").alpaca({
        });
    }, []);

    return <>
        <h2>Alpaca Form</h2>
        <div id="form"/>
    </>;
}

webpack compiles this but in the browser I see this message:

jquery__WEBPACK_IMPORTED_MODULE_1___default(...)(...).alpaca is not a function

While running "npm start", the browser error shows: ReferenceError: jQuery is not defined.

2

There are 2 answers

9
Oussama BEN MAHMOUD On

Alpaca requires handlebars.js so you need to import it before importing alpaca.js. Can you try it and tell if this works for you?

0
Albert Gevorgyan On

Looks like I have found a solution that works in a Spring Boor application. First, I create a static js script with only one function:

function alpacaForm(tag, config) {
    $(tag).alpaca(config);
}

Then I include this script in index.html, following all Alpaca dependencies:

    <!-- dependencies (jquery, handlebars and bootstrap) -->
    <script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script>
    <link type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

    <!-- alpaca -->
    <link type="text/css" href="//cdn.jsdelivr.net/npm/[email protected]/dist/alpaca/bootstrap/alpaca.min.css" rel="stylesheet"/>
    <script type="text/javascript" src="//cdn.jsdelivr.net/npm/[email protected]/dist/alpaca/bootstrap/alpaca.min.js"></script>
    <script type="text/javascript" src="./js/alpacaForm.js"></script>

Then I just call alpacaForm in my React app:

export default function Form() {
    useEffect(() => {
        alpacaForm("#form", {
               "schema": {
                   ...
               },
               "options": {
                   ...
               }
           }
        );
    }, []);

    return <>
        <h2>Alpaca Form</h2>
        <div id="form"/>
    </>;
}

See the source code here: https://gitlab.com/AlbertGevorgyan/bootreact