Skip to content

Instantly share code, notes, and snippets.

@taniagreen
Last active December 23, 2019 11:32
Show Gist options
  • Save taniagreen/b560976fa7f38f7ddcc67b2b9416b113 to your computer and use it in GitHub Desktop.
Save taniagreen/b560976fa7f38f7ddcc67b2b9416b113 to your computer and use it in GitHub Desktop.
Pass parameters from PHP to React component - data-* attributes
/// userPage.php ///
// define your parameters
$post_id = get_the_ID() ?? null;
$post_title = get_the_title() ?? '';
// add parameters as data-* attributes
return "<div data-post-id={$post_id} data-post-title={$post_title} class=\"userApp\"></div>";
/// App.jsx ///
const userApp = document.getElementById('userApp');
// data-* attributes are passed by using {...userApp.dataset}.
ReactDOM.render(<UserContainer {...userApp.dataset} />, userApp);
/// userContainer.jsx ///
class UserContainer extends React.Component {
constructor(props) {
super(props);
console.log(this.props.dataPostId); // here it is, just as a usual prop!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment