Pass variable to react

Option 1: Pass via a global JS variable (Recommended)

<?php
  $id = 123; // or from $_GET['id'], database, etc.
?>
<!DOCTYPE html>
<html>
  <head>
    <script>
      window.APP_CONFIG = {
        id: <?php echo json_encode($id); ?>
      };
    </script>
    <script crossorigin src="/assets/index-CMEaKdhP.js"></script>
    <link rel="stylesheet" crossorigin href="/assets/index-_BL4jukc.css">
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

const id = window.APP_CONFIG?.id;
console.log('ID from PHP:', id);

// Example: fetch data from API
useEffect(() => {
  if (id) {
    fetch(`/api/data?id=${id}`)
      .then(res => res.json())
      .then(setData);
  }
}, [id]);

Rate this FAQ

0 (0 Votes)