Advertisement
SRD75

[slug].tsx

Feb 22nd, 2023
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  1. import groq from 'groq'
  2. import imageUrlBuilder from '@sanity/image-url'
  3. import {PortableText} from '@portabletext/react'
  4. import client from '../../client'
  5.  
  6. function urlFor (source) {
  7. return imageUrlBuilder(client).image(source)
  8. }
  9.  
  10. const ptComponents = {
  11. types: {
  12. image: ({ value }) => {
  13. if (!value?.asset?._ref) {
  14. return null
  15. }
  16. return (
  17. <img
  18. alt={value.alt || ' '}
  19. loading="lazy"
  20. src={urlFor(value).width(320).height(240).fit('max').auto('format')}
  21. />
  22. )
  23. }
  24. }
  25. }
  26.  
  27. const Post = ({post}) => {
  28. const {
  29. title = 'Missing title',
  30. name = 'Missing name',
  31. categories,
  32. authorImage,
  33. body = []
  34. } = post
  35. return (
  36. <article>
  37. <h1>{title}</h1>
  38. <span>By {name}</span>
  39. {categories && (
  40. <ul>
  41. Posted in
  42. {categories.map(category => <li key={category}>{category}</li>)}
  43. </ul>
  44. )}
  45. {authorImage && (
  46. <div>
  47. <img
  48. src={urlFor(authorImage)
  49. .width(50)
  50. .url()}
  51. alt={`${name}'s picture`}
  52. />
  53. </div>
  54. )}
  55. <PortableText
  56. value={body}
  57. components={ptComponents}
  58. />
  59. </article>
  60. )
  61. }
  62.  
  63. const query = groq`*[_type == "post" && slug.current == $slug][0]{
  64. title,
  65. "name": author->name,
  66. "categories": categories[]->title,
  67. "authorImage": author->image
  68. }`
  69.  
  70. export async function getStaticPaths() {
  71. const paths = await client.fetch(
  72. groq`*[_type == "post" && defined(slug.current)][].slug.current`
  73. )
  74.  
  75. return {
  76. paths: paths.map((slug) => ({params: {slug}})),
  77. fallback: true,
  78. }
  79. }
  80.  
  81. export async function getStaticProps(context) {
  82. // It's important to default the slug so that it doesn't return "undefined"
  83. const { slug = "" } = context.params
  84. const post = await client.fetch(`
  85. *[_type == "post" && slug.current == $slug][0]{title, "name": author->name}
  86. `, { slug })
  87.  
  88. return {
  89. props: {
  90. post
  91. }
  92. }
  93. }
  94.  
  95. export default Post
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement