I'm working on a project where clicking on four different tabs display different information. I'm trying to lift up state from child client component to parent server component but I keep getting errors. Clicking on the "All Courses" tab for instance should set the state to "all" from the client component and make it accessible in the parent component.
Child Component (Client component):
export default function CategoryTab(update){
const [category, setCategory] = useState("all")
const handleClick = (category) => {
setCategory(category)
let update = category
return update
}
return (
<React.Fragment>
<div className={styles.category_tab}>
<ul>
<li onClick={() => handleClick("all")}>All Courses</li>
<li onClick={() => handleClick("doctorate")}>Doctorate Courses</li>
</ul>
<ul>
<li onClick={() => handleClick("diploma")}>Diploma Courses</li>
<li onClick={() => handleClick("certificate")}>Certificate Courses</li>
</ul>
</div>
</React.Fragment>
)
}
Parent component (server component):
export default function CourseList(){
const getCategory = async (category) => {
"use server"
let response = await category
console.log(response)
return response
}
return (
<React.Fragment>
<section className={styles.courses_container}>
<h1>programmes</h1>
<h2>Below are the different available programmes at XYZ</h2>
<CategoryTab update = {getCategory}/> //CHILD COMPONENT
{category==="all" && <p>all</p>}
{category==="doctorate" && <p>doctorate</p>}
{category==="all" && <p>all</p>}
</section>
</React.Fragment>
)
}
Below is the next.js config file:
const nextConfig = {
experimental: {
serverActions: true,
},
}
You are actually passing function to your child component and you should pass a value to it instead of
let update = category
whatever this is
Here is an example with type script :
Parent component
type MyFunctionType = (parameter: string) => void;
export default async function Parent() {
const myFunction: MyFunctionType = async (parameter) => {
"use server";
console.log(`Received parameter: ${parameter}`);
};
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<Child myFunction={myFunction} />
</main>
)
Child component "client"
"use client"
type ChildProps = {
myFunction: MyFunctionType;
};
const Child = (props: ChildProps) => {
const { myFunction } = props;
return (
<button onClick={() => myFunction("your state")} >
CLICK
</button>
);
this will give data to myFunction and log in your terminal.