prismicio / prismic-react

React components and hooks to fetch and present Prismic content
https://prismic.io/docs/technologies/homepage-reactjs
Apache License 2.0
153 stars 40 forks source link

Pass props to individual slice in Next.js #172

Closed fatpig0416 closed 1 year ago

fatpig0416 commented 1 year ago

Hi, all. Hope you are doing well.

I am going to integrate Prismic into my next.js project. Now, I am rendering prismic content to my pages but sometimes I need to pass my custom props to slice from parent component. For example, I have a slice called process and I want to pass props called onClickItem.

How can I pass this prop to the slice via SliceZone. Does anybody have any idea or any experience?

angeloashmore commented 1 year ago

Hey @fatpig0416, there are a few ways to do this. The most straightforward way is to use <SliceZone>’s context prop.

You can pass any data to context, including functions, and access it within a Slice component from the context prop.

You can pass context like this to <SliceZone>:

const onClickItem = () => console.log("Clicked!")

<SliceZone
  slices={page.data.slices}
  context={{ onClickItem }}
/>

And in your Slice component, use it like this:

// slices/Text/index.js

const TextSlice = ({ slice, context }) => {
  return (
    <button onClick={context.onClickItem}>Click me</button>
  )
}

You can learn more about the component and the context prop here: https://prismic.io/docs/technical-reference/prismicio-react#slicezone

If you have any questions, feel free to post them here. I’m going to close this issue in the meantime. 🙂

fatpig0416 commented 1 year ago

I appreciate your help. @angeloashmore