0

I am fairly new to coding with React. I'm trying to use an if / else statement and then use the result within the body of the content. Also, another bit of important info is that this is linked to Sanity CMS so I am pulling the content from a database. I think I am missing something quite simple but am using the if statement incorrectly from a React perspective. I've read up on the docs but need some new perspective.

I am also getting one error as well: return null = A 'return' statement can only be used within a function body.

import { SanityContent } from "../../components/sanityContent";
import { Post, getPosts } from "../../utils/getPosts";
import { useDomain } from "../../utils/domain";

const post = getPosts();

if (post.title = 'Cookie Policy'){
   <div> post.legalDoc </div>
}
if (!post) {
   return null;
}


function CookiePolicy() {
  return (
    <Layout>
      <SanityContent content={post.legalDoc} />

Any ideas?

1 Answers1

0

Yeah this is weird one, but also pretty simple.

A solution for your code:

import { SanityContent } from "../../components/sanityContent";
import { Post, getPosts } from "../../utils/getPosts";
import { useDomain } from "../../utils/domain";

function CookiePolicy() {
  const test = () => {
    const post = getPosts();

    if (post.title === "Cookie Policy") {
      console.log("YUP");
      return <div>{post.legalDoc}</div>;
    } else {
      console.log("NOPE");
      return null;
    }
  };

  return <div>{test()}</div>;
}

I've also made a codesandbox to demonstrate.

Also, if you ever need an asynchronous if-check function within your component, I've answered a similar question here: objects are not valid as a react child when trying to render component based off of AsyncStorage React-Native

Christian
  • 356
  • 1
  • 5
  • 14
  • Thank you for the help! i'm working my way through this - now some errors on the dataset side haha one issue at a time :) – Elektra Murphy Apr 22 '21 at 07:11
  • 1
    No problem Elektra, glad I could help! :) And oh man good luck, I'll be here dwelling in the questions so maybe I'll see you again! hahaha – Christian Apr 22 '21 at 07:16