Wednesday, September 28, 2022
HomeWordPress DevelopmentFind out how to use react in frontend of dynamic blocks?

Find out how to use react in frontend of dynamic blocks?


My objective is to make use of attributes defaulted I block.json or modified in block-editor in frontend. In block-editor all the things works excellent. I can show attributes, change them, add new rows in array or delete an array.
However in frontend… I wouldn’t have any date in database

<!-- wp:my-pluggin/my-accordation {"clicked":null} /-->

however after re-writting attributes under 'render_callback' and use <?php echo get_block_wrapper_attributes(); ? I can see them on front-end.

The final step is to my react software convert it to my software.

On frontend I can see there may be wp_enquequed script frontend.js
which ought to take div and rework it into react part. However, the script don’t something.

pluggin.php

  operate render_callback_function($blockattributes, $content material) {
    if(!is_admin()){
    wp_enqueue_script( 'attentionFrontend', plugin_dir_url(__FILE__) . 'construct/frontend.js', array(
      'wp-blocks', 'wp-element', 'wp-editor'    ) );
    wp_enqueue_style('attentionFrontendStyles', plugin_dir_url(__FILE__) . 'construct/frontend.css');
      } 
      
      
 ob_start(); ?>
<div class="update-me" <?php echo get_block_wrapper_attributes(); ?>>
<pre model="show: block;"><?php echo wp_json_encode($blockattributes) ?></pre>
</div>

<?php return ob_get_clean();
  }
}

frontend.js

import React, {useState} from 'react'
import ReactDOM from 'react-dom'
import "./frontend.scss"

const divsToUpdate = doc.querySelectorAll(".update-me")

divsToUpdate.forEach(operate(div) {
  const information = JSON.parse(div.querySelector("pre").innerHTML)
  ReactDOM.render(<Frontend {...information} />, div)
  div.classList.take away("update-me")
})

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments