Last active
December 23, 2019 11:32
-
-
Save taniagreen/b560976fa7f38f7ddcc67b2b9416b113 to your computer and use it in GitHub Desktop.
Pass parameters from PHP to React component - data-* attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// 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