How to display Blockly in React

1.3k Views Asked by At

I tried to use blockly in my React project. The installation works fine, I can run my project without any error but blockly does not appear. I have a big empty block and I cannot figure out why. I kept the same components as the github project, I used the exact same example displayed on github (except I put the code in on of my own component).

When I open the console, I can see that the blocky elements are there but I cannot see them and use them. I need to create custom elements in blockly and to be able to use it to generate code.

My page (the GenericPage is a component containing the layout of my webiste)

import React from 'react';
import GenericPage from '../_components/Layout/GenericPage';
import Blockly from 'node-blockly/browser';
import BlocklyDrawer,{ Block,Category } from 'react-blockly-drawer';

const BlocklyAltPage = (props) => {
    const helloWorld = {
        name: 'HelloWorld',
        category: 'Demo',
        block: {
            init: function () {
                this.jsonInit({
                    message0: 'Hello %1',
                    args0: [
                        {
                            type: 'field_input',
                            name: 'NAME',
                            check: 'String',
                        },
                    ],
                    output: 'String',
                    colour: 160,
                    tooltip: 'Says Hello',
                });
            },
        },
        generator: (block) => {
            const message = `'${block.getFieldValue('NAME')}'` || '\'\'';
            const code = `console.log('Hello ${message}')`;
            return [code,Blockly.JavaScript.ORDER_MEMBER];
        },
    };

    return (
        <GenericPage>
            <BlocklyDrawer
                tools={[helloWorld]}
                onChange={(code,workspace) => {
                    console.log(code,workspace);
                }}
                language={Blockly.JavaScript}
                appearance={
                    {
                        categories: {
                            Demo: {
                                colour: '270'
                            },
                        },
                    }
                }
            >
                <Category name="Variables" custom="VARIABLE" />
                <Category name="Values">
                    <Block type="math_number" />
                    <Block type="text" />
                </Category>
            </BlocklyDrawer>,
        </GenericPage>
    );
}

export default BlocklyAltPage;
1

There are 1 best solutions below

0
On

Make sure the div where Blockly is injected has a specified height. You need to do this because the div itself doesn't have any. This might be the cause of your issue if you say you can see Blockly in the console but not in the page.