Shortcode attributes in Wordpress plugin with React
Wordpress way to load custom data for script is using wp_localize_script
function.
You could rewrite your shortcode function by the way
add_shortcode( 'my_app', 'my_app' );/** * Registers a shortcode that simply displays a placeholder for our React App. */function my_app( $atts = array(), $content = null , $tag = 'my_app' ){ add_action( 'wp_enqueue_scripts', function() use ($atts) { wp_enqueue_script( 'my-app', plugins_url( 'build/index.js', __FILE__ ), array( 'wp-element' ), time(), true ); wp_localize_script( 'my-app', 'myAppWpData', $atts ); }); return '<div id="app">Loading...</div>';}
Then you could use shortcode settings object via JavaScript by the way:
window.myAppWpData['form'] // if you set form as shortcode param
Then you could set this options as props param for your react WP_App component.
And then you could render your WP_APP content conditionally to its shortcode param:
Main render:
render( <WP_App shortcodeSettings={window.myAppWpData} />, document.getElementById('app'));
and how can I display a content according to this attribute in reactside?
You could use conditional logic according to shortcode atts values.More details about conditional React logic you could find on official documenction page
https://reactjs.org/docs/conditional-rendering.html
WP_APP render:
you could use props.shortcodeSettings
inside WP_APP render()
function to build any logic your want to display your component.
render() { return ( // you could use props.shortcodeSettings to build any logic // ...your code )}
If you want to have multiple shortcodes on the page.
You could consider to add uniqid( 'my-app' )
to script handle name
function my_app( $atts = array(), $content = null, $tag = 'my_app' ) { $id = uniqid( 'my-app' ); add_action( 'wp_enqueue_scripts', function () use ( $atts, $id ) { wp_enqueue_script( "my-app", plugins_url( 'build/index.js', __FILE__ ), array( 'wp-element' ), time(), true ); wp_localize_script( "my-app", "myAppWpData-$id", $atts ); } ); return sprintf( '<div id="app-%1" data-my-app="%1">Loading...</div>', $id );}
For this way - you could implement for your index.js
file logic for multiple apps,
const shortcodesApps = document.querySelectorAll('[data-my-app]');shortcodesApps.forEach((node) => { const nodeID = node.getAttribute('data-my-app'); const shortcodeSettings = window[`myAppWpData-${nodeID}`]; render( <WP_App shortcodeSettings={shortcodeSettings} />, node );})