I need some help and have been stuck here too long. I am new to react, but not completely new to Wordpress.

My example works fine using shortcodes, but I thought it's time to convert the shortcodes to block types.

I want to display an embedded map with leaflet. But I need to call a JS method (initMap()) after creating the content. This works fine if I use the browser console. However it is not working if I generate a <script> tag in the block.js. Even a console.log('test!') seems not to be executed.

I can't think my head around this. What would be a good approach for this? Is there something like a callback after render?

My index.php:

function random_image_enqueue_block_editor_assets() {
        plugins_url( 'block.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element' )
    wp_enqueue_script('leaflet',  plugins_url( 'leaflet.js', __FILE__ ));
    wp_enqueue_script('spotmap',  plugin_dir_url( __FILE__ ) . 'maphandler.js', array('jquery'));
    wp_enqueue_style( 'leaflet', plugin_dir_url( __FILE__ ) . 'leaflet.css');
add_action( 'enqueue_block_assets', 'random_image_enqueue_block_editor_assets' );

the block.js:

( function( blocks, element ) {
    var el = element.createElement;

    function renderMap( props ) {
        return el('div',{},
            el('div',{id: 'spotmap-container', style: {height: 400+'px'}}),
            el('script',{type: 'text/javascript'},'initMap();')
    blocks.registerBlockType( 'spotmap/spotmap', {
        title: 'Spotmap',
        icon: 'location-alt',
        category: 'embed',
        edit: function( props ) {
            return renderMap( props )

        save: function( props ) {
            return renderMap( props );
    } );
} )(

and the maphandler.js:

function initMap() {
    var spotmap = L.map('spotmap-container',{ fullscreenControl: true,});
    var OpenTopoMap = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
        maxZoom: 16,
        attribution: 'Map: &copy; <a href="https://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)'
    spotmap.setView([51.505, -0.09], 13);
    // loadData();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.