Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add hydrateRoot when react ssr enabled #387

Merged
merged 5 commits into from
May 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/Console/InstallsInertiaStacks.php
Original file line number Diff line number Diff line change
Expand Up @@ -333,9 +333,11 @@ protected function installInertiaReactSsrStack()
if ($this->option('typescript')) {
copy(__DIR__.'/../../stubs/inertia-react-ts/resources/js/ssr.tsx', resource_path('js/ssr.tsx'));
$this->replaceInFile("input: 'resources/js/app.tsx',", "input: 'resources/js/app.tsx',".PHP_EOL." ssr: 'resources/js/ssr.tsx',", base_path('vite.config.js'));
$this->configureReactHydrateRootForSsr(resource_path('js/app.tsx'));
} else {
copy(__DIR__.'/../../stubs/inertia-react/resources/js/ssr.jsx', resource_path('js/ssr.jsx'));
$this->replaceInFile("input: 'resources/js/app.jsx',", "input: 'resources/js/app.jsx',".PHP_EOL." ssr: 'resources/js/ssr.jsx',", base_path('vite.config.js'));
$this->configureReactHydrateRootForSsr(resource_path('js/app.jsx'));
}

$this->configureZiggyForSsr();
Expand All @@ -344,6 +346,42 @@ protected function installInertiaReactSsrStack()
$this->replaceInFile('/node_modules', '/bootstrap/ssr'.PHP_EOL.'/node_modules', base_path('.gitignore'));
}

/**
* Configure the application JavaScript file to utilize hydrateRoot for SSR.
*
* @param string $path
* @return void
*/
protected function configureReactHydrateRootForSsr($path)
{
$this->replaceInFile(
<<<'EOT'
import { createRoot } from 'react-dom/client';
EOT,
<<<'EOT'
import { createRoot, hydrateRoot } from 'react-dom/client';
EOT,
$path
);

$this->replaceInFile(
<<<'EOT'
const root = createRoot(el);

root.render(<App {...props} />);
EOT,
<<<'EOT'
if (import.meta.env.DEV) {
createRoot(el).render(<App {...props} />);
return
}

hydrateRoot(el, <App {...props} />);
EOT,
$path
);
}

/**
* Configure Ziggy for SSR.
*
Expand Down