Usare ReactJS in WordPress


class react
    {
        
        public function __construct()
        {
            add_filter('script_loader_tag', array(&$this, 'add_babel_type'), 10, 3);
            add_action('wp_enqueue_scripts', array($this, 'load_scripts_styles'));
        }

        function load_scripts_styles()
        {
            wp_register_script('react', 'https://unpkg.com/react@16.9.0/umd/react.development.js', array(), "16.9.0");
            wp_register_script('react-dom', 'https://unpkg.com/react-dom@16/umd/react-dom.development.js', array('react'), "16");
            wp_register_script('babel', 'https://unpkg.com/@babel/standalone/babel.min.js', array('react'), "1");
            wp_register_script('react-jsx', plugin_dir_path(__FILE__) . 'includes/js/react.jsx', array('react'), "1.0");
            $this->load_assets();
        }

        public function load_assets()
        {
            wp_enqueue_script('react');
            wp_enqueue_script('react-dom');
            wp_enqueue_script('babel');
            wp_enqueue_script('react-jsx');

            $api_settings = array(
                'security' => wp_create_nonce('mynonce'),
            );

            wp_localize_script('react-jsx', 'react_api_settings', $api_settings);
        }

        // Add "babel" type to script
        function add_babel_type($tag, $handle, $src)
        {
            if ($handle !== 'react-jsx') {
                return $tag;
            }

            return '' . "\n";
        }
    }
<div id="root_react"></div>

<script type="text/babel">
    ReactDOM.render(<Test />, document.getElementById('root_react'));
</script>

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *