Home > database >  JSX syntax inside the return function of a component causing a blank white screen on the browser
JSX syntax inside the return function of a component causing a blank white screen on the browser

Time:02-18

this is a component of a mern crud app. Post creation works and were displaying on the browser and mongo DB. but while implementing update, JSX of one of the component is causing the app to crash. Please check the following component

import React from 'react'
import Post from './Post/Post'
import { useSelector } from 'react-redux';

const Posts = ({ setCurrentId }) => {

  const posts = useSelector((state) => state.posts);


 console.log(posts);
  return (
    !posts.length ? "No Posts, Make a post and come back" : (
      <div className='outer'>
        {
          posts.map((post)=>(
            <div className = 'inner' key= {post._id}>
            <Post post = {post} setCurrentId = {setCurrentId} />
            </div>
          ))
        }
      </div>
    )      
)      
}

I am getting these errors ONLY in console, visual code does not show any error for client and server side. Error in console

hit and trial : if I comment out everything inside the outer div, I can see part of the app(one component of two components in the App.js), if I paste it back I can see the whole app, but when I refresh it goes back to black white screen.

guys plese let me know whats causing this, I guessing it is to do with the syntax, but I tried a lot o things but still not working.

CodePudding user response:

Inside a component your return need to be XML (JSX = JS XML)

So, your return must be begin by a and finish by the close of the same element .

In your case :

return (
<> //this is fragment, see react doc for that
 {productsData.map((product) => {
    return (
      <>
        {posts.length === 0 ? 
          "No Posts, Make a post and come back"
        : (
          <div className="outer">
            {posts.map((post) => (
              <div className="inner" key={post._id}>
                <Post post={post} setCurrentId={setCurrentId} />
              </div>
            ))}
          </div>
        )}
      </>
    );
  })}
</>
)

CodePudding user response:

Does state.posts exist in your store? And you need to return a JSX element, always

To have a safe render, try;

import React from "react";
import Post from "./Post/Post";
import { useSelector } from "react-redux";
import "./Posts.css";

const Posts = ({ setCurrentId }) => {
    const posts = useSelector((state) => state.posts);
    console.log(posts);
    return (
       <>
           {(posts.map = (post) => {
               let obj = {
                   post: { post },
                   setCurrentId: { setCurrentId }
               };
               return <Post obj={obj} />
           }
           )}
       </>
   );
};

export default Posts;
  • Related