Pyscript with nextjs
Answered
In&Out posted this in #help-forum
In&OutOP
Hey, is it possible to use pyscript with nextjs?
Answered by In&Out
import { useEffect, useState } from "react";
export default function Home() {
const [hydrated, setHydrated] = useState(false);
useEffect(() => {
setHydrated(true);
}, []);
if (!hydrated) {
// Returns null on first render, so the client and server match
return null;
}
return (
<div>
test
<py-script>
for i in range(9):{"\n"} print(i){"\n"}
{"\n"}
def func():{"\n"} print('function works'){"\n"}
</py-script>
</div>
);
}
38 Replies
What did you try, what did work/didn't work
it's supposed to work in the broswser, so it probably works, but you'll have to explore how
In&OutOP
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import Script from "next/script";
import { NextScript } from "next/document";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<Script
defer
src="https://pyscript.net/latest/pyscript.js"
strategy="beforeInteractive"
/>
);
}
a dumb try ngl lol
cool, did you try to run some Python with that ?
In&OutOP
semmes to be blending Pages and App Router, can you try on a freshly created Next.js app maybe ?
In&OutOP
i did
are you sure the issue is related with PyScript?
In&OutOP
let me remove it
yup, it is
what's NextScript from "next/document" ?
In&OutOP
works without it
idk i was just following this https://fabiorosado.dev/blog/running-pyscript-in-react/
this tutorial is for the pages router you should try with the pages router rather than the app router then
In&OutOP
ah alr, how to get pages folder in next 14?
In&OutOP
oh just that?
alr will do
yep pages router is still working fine and will for a long while
In&OutOP
did it, tho it doesnt work
export default function Home() {
return (
<div>
test
<py-script>
for i in range(9): print(i) def func(): print('function works')
</py-script>
</div>
);
}
Property 'py-script' does not exist on type 'JSX.IntrinsicElements'.
do i need to downgrade nextjs or somethig
In&OutOP
oh crap, it works
In&OutOP
import { useEffect, useState } from "react";
export default function Home() {
const [hydrated, setHydrated] = useState(false);
useEffect(() => {
setHydrated(true);
}, []);
if (!hydrated) {
// Returns null on first render, so the client and server match
return null;
}
return (
<div>
test
<py-script>
for i in range(9):{"\n"} print(i){"\n"}
{"\n"}
def func():{"\n"} print('function works'){"\n"}
</py-script>
</div>
);
}
Answer
yeah I was expecting something like that you need client-only components
In&OutOP
okay thanks