Blog>
Snippets

Passing Props to React Server Components

Explain how to pass props from a parent component to a child server component and how to use those props serverside within Next.js 14.
// ParentComponent.server.jsx
import ChildComponent from './ChildComponent.server.jsx';

export default function ParentComponent(props) {
  const parentData = 'Data from parent';
  // Here we pass parentData as a prop to the ChildComponent
  return <ChildComponent parentProp={parentData} />;
}
In a parent server component, import the child server component and pass the desired data as props while rendering the child component.
// ChildComponent.server.jsx
export default function ChildComponent({ parentProp }) {
  // Here we can use the parentProp that was passed from the ParentComponent
  return (
    <div>
      <p>The prop passed from the parent is: {parentProp}</p>
    </div>
  );
}
In the child server component, receive the props from the parent component and use it within the component's render method.
// pages/_middleware.js
import { NextResponse } from 'next/server';

export async function middleware(request) {
  // Server-side logic before sending to the getServerSideProps or server components
  return NextResponse.next();
}
If needed, set up a middleware for your Next.js application to handle server-side logic or authorization before rendering server components.
// pages/ExamplePage.jsx
import ParentComponent from '../components/ParentComponent.server.jsx';

export default function ExamplePage(props) {
  // Here you could have getServerSideProps or getStaticProps to fetch data
  // Then you render the ParentComponent server component like so:
  return <ParentComponent someProp={props.dataFromServer} />;
}
This is how you would use the ParentComponent server component within a page.