Error while moving on to other page in react - javascript

Currently am writing a full stack website, which uses Nodejs and Mongodb for Backend and reactjs for Frontend. I am having a problem in react. As I am new to developing, my explanation of the problem won't be accurate, forgive me for this.
Coming to the error, when am at my home page, it gets every picture and all the stuff perfectly, but when I go to profile page, the pictures wont get updated and they wont appear. I don't know why, please help me....
This is my feed page
import "./feed.css";
import Post from "../post/Post";
import Share from "../share/Share";
import { useState } from "react";
import { useEffect } from "react";
import axios from 'axios';
export default function Feed({username}) {
const [posts,setPosts]=useState([]);
const [texts,setTexts]=useState([]);
useEffect(()=>{
const fetchPosts=async ()=>{
const res=username?
await axios.get("posts/profile/"+username):
await axios.get("posts/timeline/63c29c2fe9a410383d4bcb98");
setPosts(res.data);
};
fetchPosts();
},[]);
return (
<div className="feed">
<div className="feedWrapper">
<Share/>
{posts.map((p)=>(
<Post key={p._id} post={p}/>
))}
</div>
</div>
)
}
This is my Profile.jsx
import "./profile.css"
import Topbar from "../../components/topbar/Topbar";
import Sidebar from "../../components/sidebar/Sidebar";
import Feed from "../../components/feed/Feed";
import Rightbar from "../../components/rightbar/Rightbar";
import { useEffect } from "react";
import axios from "axios";
import { useState } from "react";
export default function Profile() {
const [user,setUser]= useState({});
useEffect(()=>{
const fetchUser=async ()=>{
const res=await axios.get(`/users/?username=Bannu`);
setUser(res.data);
};
fetchUser();
},[]);
return (
<>
<Topbar/>
<div className="profile">
<Sidebar/>
<div className="profileRight">
<div className="profileRightTop">
<div className="profileCover">
<img className="profileCoverImg" src={user.coverPicture||"assets/person/noCover.jpeg"} alt="" />
<img className="profileUserImg"src="assets/person/7.jpeg" alt="" />
</div>
<div className="profileInfo">
<h4 className="profileInfoName">{user.username}</h4>
<span className="profileInfoDesc">{user.desc}</span>
</div>
</div>
<div className="profileRightBottom">
<Feed username='Bannu'/>
<Rightbar user={user}/>
</div>
</div>
</div>
</>
)
}
This is Post.jsx
import "./post.css";
import { MoreVert } from "#material-ui/icons";
import axios from 'axios';
import { useState,useEffect } from "react";
import {format} from 'timeago.js';
import { Link } from "react-router-dom";
export default function Post(post) {
const [like,setLike]=useState(post.post.likes.length);
const [isLiked,setIsLiked]=useState(false);
const [user,setUser]=useState({});
const likeHandler=()=>{
setLike(isLiked?like-1:like+1);
setIsLiked(!isLiked);
};
useEffect(()=>{
const fetchUser=async ()=>{
const res=await axios.get(`/users?userId=${post.post.userId}`);
setUser(res.data);
};
fetchUser();
},[post.post.userId]);
return (
<div className="post">
<div className="postWrapper">
<div className="postTop">
<div className="postTopLeft">
<Link to={`profile/${user.username}`}>
<img className="postProfileImg"src={user.profilePicture||"assets/person/noAvatar.jpeg"} alt="" />
</Link>
<span className="postUsername">{user.username}</span>
<span className="postDate">{format(post.post.createdAt)}</span>
</div>
<div className="postTopRight">
<MoreVert/>
</div>
</div>
<div className="postCenter">
<span className="postText">{post?.desc}</span>
<img className="postImg" src={post.post.img} alt="" />
</div>
<div className="postBottom">
<div className="postBottomLeft">
<img className="likeIcon" src="assets/like.png" onClick={likeHandler} alt="" />
<img className="likeIcon"src="assets/heart.jpeg" onClick={likeHandler} alt="" />
<span className="postLikeCounter">{like} people like it</span>
</div>
<div className="postBottomRight">
<span className="postCommentText">{post.comment} comments</span>
</div>
</div>
</div>
</div>
)
}
This is share.jsx
import "./share.css"
import {PermMedia,Label, Room, EmojiEmotions} from '#material-ui/icons'
export default function Share() {
return (
<div className="share">
<div className="shareWrapper">
<div className="shareTop">
<img className="shareProfileImg" src="assets/person/1.png" alt="" />
<input type="text"
placeholder="What's in your mind?"
className="shareInput"
/>
</div>
<hr className="shareHr" />
<div className="shareBottom">
<div className="shareOptions">
<div className="shareOption">
<PermMedia htmlColor="tomato" className="shareIcon"/>
<span className="shareOptionText">Photo or Video</span>
</div>
<div className="shareOption">
<Label htmlColor="blue"className="shareIcon"/>
<span className="shareOptionText">Tag</span>
</div>
<div className="shareOption">
<Room htmlColor="green" className="shareIcon"/>
<span className="shareOptionText">Location</span>
</div>
<div className="shareOption">
<EmojiEmotions htmlColor="goldenrod" className="shareIcon"/>
<span className="shareOptionText">Feeling</span>
</div>
</div>
<button className="shareButton">Share</button>
</div>
</div>
</div>
)
}
And these are the pictures of home and particular profile pages Home Particular profile page. You can observe that in the profile page the image of a post is missing.
Help me ....

Related

Next js Problem with sending props in through

So i have three files, and i am using Next.Js.
Those 3 files are _app.js, Layout.js, Navbar.js
_app.js
import '../styles/globals.css'
import '../styles/navbar.css'
import Layout from '../components/Layouts/Layout'
function MyApp({ Component, pageProps }) {
return (
<Layout primary_super='darkMode_Primary' secondary_super='darkMode_Secondary'>
<Component {...pageProps} />
</Layout>
)
}
export default MyApp
Layout.js
import Navbar from '../comps/Navbar'
import pt from 'prop-types';
export default function Layout({ children }, props) {
return (
<>
<Navbar primary={props.primary_super} secondary={props.secondary_super}/>
<main>{children}</main>
</>
)
}
Layout.pt = {
primary_super: pt.string,
secondary_super: pt.string,
};
Layout.defaultProps = {
primary_super: 'darkMode_Primary',
secondary_super: 'darkMode_Secondary',
}
Navbar.js
import theme from "../Data/theme"
import pt from 'prop-types';
export default function Navbar(props) {
const Primary = theme[props.primary]
const Secondary = theme[props.secondary]
return (
<div class="NAV" id="NAV" style={Primary}>
<div class="NAV_BOX_FULL NAV_LEX" style={Secondary}>
<img src="/NAV_img/cat.png" alt="" class="NAV_logo1 NAV_logo"/>
<h3 class="NAV_head">SilenxIka</h3>
</div>
<hr class="NAV_block"/>
<div class="NAV_BOX">
<img src="/NAV_img/home.png" alt="" class="NAV_logo"/>
<h3 class="NAV_head">Home</h3>
</div>
<div class="NAV_BOX">
<img src="/NAV_img/discord.png" alt="" class="NAV_logo"/>
<h3 class="NAV_head">Discord</h3>
</div>
<div class="NAV_BOX">
<img src="/NAV_img/about.png" alt="" class="NAV_logo"/>
<h3 class="NAV_head">About</h3>
</div>
<div class="NAV_BOX">
<img src="/NAV_img/projects.png" alt="" class="NAV_logo"/>
<h3 class="NAV_head">Projects</h3>
</div>
<div class="NAV_BOX">
<img src="/NAV_img/contact.png" alt="" class="NAV_logo NAV_SUS"/>
<h3 class="NAV_head">Contact Me</h3>
</div>
</div>
)
}
Navbar.pt = {
primary: pt.string,
secondary: pt.string,
};
All i want to do is, do some logic in _app.js then send two strings into Layout.js and then finally in Navbar.js to access those two strings, as you can see i tried to use props but it didn't work well.

How to pass a state to a Parent component if I have a button triggering the state in the 2nd Child in React

Hi there,
The issue that I faced recently is the next:
I have a parent component MainPage, that has child components ModalJoin (is not shown by default) and ExploreProjects in it. This ExploreProjects component has its own child component ProjectCard which has a button that is supposed to change a state so ModalJoin is shown.
Does anyone have a solution of how do I bind all these, so when the button is clicked ->useState changes to true and ModalJoin pops up? Been trying to link them properly the whole day but still didn't find a solution.
Would appreciate any help!
Have the following files:
Main page
import React, {useState} from 'react'
import ExploreProjects from './ExploreProjects'
import ModalJoin from './ModalJoin'
export default function MainPage() {
const [isOpened, setIsOpened] = useState(false)
return (
<div>
<div className='app'>
<div className="app__body">
<ExploreProjects/>
</div>
</div>
<ModalJoin openModal={isOpened} onClose={() => setIsOpened(false)}/>
</div>
)
}
ExploreProjects
import React from 'react'
import './ExploreProjects.css'
import ProjectCard from './ProjectCard'
function ExploreProjects() {
return (
<div className='explore__projects'>
<div className="filters__section">
<div className='filter__item'>
<h3>Location</h3>
<img src="/images/chevronDown.svg" alt=""/>
</div>
<div className='filter__item'>
<h3>Industry</h3>
<img src="/images/chevronDown.svg" alt=""/>
</div>
<div className='filter__item'>
<h3>Company</h3>
<img src="/images/chevronDown.svg" alt=""/>
</div>
<div className='filter__item'>
<h3>Complexity</h3>
<img src="/images/chevronDown.svg" alt=""/>
</div>
<div className='filter__item'>
<h3>Duration</h3>
<img src="/images/chevronDown.svg" alt=""/>
</div>
</div>
<div className="projects__section">
<ProjectCard />
<ProjectCard />
<ProjectCard />
<ProjectCard />
<ProjectCard />
<ProjectCard />
</div>
</div>
)
}
export default ExploreProjects
ProjectCard
import React, {useState} from 'react'
import './ProjectCard.scss'
export default function ProjectCard({ src, logo, headline, companyName,
complexity, description, projectType, tag }) {
const [setIsOpened] = useState(false)
return (
<div className='project__card'>
<div className="project__card__header">
<img src="/images/rehauIcon.png" alt="" className='company__logo' />
<h3>Logistics Project</h3>
<div className="project__card__company">
<img src="/images/buildingIcon.svg" alt="" />
<p>Rehau</p>
<p>/</p>
<img src="/images/locationIcon.svg" alt="" />
<p>Berlin</p>
</div>
<div className="project__card__complexity">
<div className="basic__complexity"></div>
<p>Basic</p>
</div>
</div>
<div className="project__card__body">
<div>
<h3>Task:</h3>
</div>
<span>Text
<button>More</button>
</span>
</div>
<div className="project__card__bottom">
<div className="project__card__time">
<p>15m ago</p>
</div>
<div className="project__card__recruitment">
<p>Job opportunity</p>
</div>
<div className="project__card__teams">
<p>1/2 teams joined</p>
</div>
<div className="project__card__tag">
<p>#supplychain</p>
</div>
</div>
<div className="project__card__right">
<img src="images/imgHero.png" alt="" className='project__video__info' />
<div onClick={ () => this.setIsOpened(true)} className="join__project__button">
<p>Join</p>
</div>
</div>
</div>
)
}
ModalJoin
import React from 'react'
export default function ModalJoin({openModal, onClose}) {
if (!openModal) return null
return (
<div>
<button onClick={onClose}>Close</button>
HEEEYYYYYY
</div>
)
}
I commented:
You'll need to pass a callback prop down <ExploreProjects onOpenModalJoin={callback} />, and then pass the same callback down from ExploreProjects down to ProjectCard. Then in project card on the button click, you would call that callback.
This is a more full explanation:
export default function MainPage() {
const [isOpened, setIsOpened] = useState(false);
const callback = () => setIsOpened(true);
...
<ExploreProjects onOpenModalJoin={callback} />
function ExploreProjects(props) {
...
<ProjectCard onOpenModalJoin={props.onOpenModalJoin} />
...
And then inside ProjectCard, you would have
onClick={props.onOpenModalJoin}
Lets go with a simple example on how to change state of a parent from a child and manipulate conditional rendering. you have to pass setState to the child and subChild as well and call it from there. That changes parent state and reflects on modal.
Code Sandbox => https://codesandbox.io/s/silent-bush-c6v4d?file=/src/App.js:0-992
Here you go, this should fix your issue.
import React, { useState } from "react";
import "./styles.css";
const ModalJoin = ({ open, close }) => {
const modal = open ? (
<div style={{ background: "pink" }}>
I am ModalJoin
<button onClick = {close}> Close Me</button>
</div>
) : null;
return modal;
};
const ExploreProjects = ({ click }) => {
return (
<div style={{ background: "orange" }}>
I am ExploreProjects
<ProjectCard click={click} />
</div>
);
};
const ProjectCard = ({ click }) => {
return (
<div style={{ background: "grey" }}>
I am ProjectCard
<button onClick={click}>click me to open modal </button>
</div>
);
};
const App = () =>
{
const [modal, setModal] = useState(false)
return (
<div className="App" style={{ background: "lightBlue" }}>
<h1>I am Parent</h1>
<ExploreProjects click = {() => setModal(true)}/>
<ModalJoin open={modal} close={() => setModal(false)} />
</div>
);
};
export default App;

Functional component is not being rendered

I am trying to display the songs but for some reason my songs component is not even being executed. The console.log statement inside the Songs component is also not being logged to console. Also no errors of any sort are detected at all.
Here is my body component from which I am calling the Songs component
import './body.css'
import React from 'react'
import Header from './Header'
import { useStateValue } from './StateProvider';
import FavoriteIcon from '#material-ui/icons/Favorite';
import PlayCircleFilledIcon from '#material-ui/icons/PlayCircleFilled';
import MoreHorizIcon from '#material-ui/icons/MoreHoriz';
import Songs from './Songs.js'
function Body( {spotify}) {
const [{recently_played},dispatch] = useStateValue();
return (
<div className="body">
<Header spotify={spotify} />
<div className="body__info">
<img src={recently_played?.images[0].url} alt=""/>
<div className="body__infotext">
<strong>PLAYLIST</strong>
<h2>On Repeat</h2>
<p>{recently_played?.description}</p>
</div>
</div>
<div className="body__songs">
<div className="body__icons">
<PlayCircleFilledIcon className="body__shuffle"/>
<FavoriteIcon fontSize="large"/>
<MoreHorizIcon />
</div>
{recently_played?.tracks.items.map(item=>{
<Songs track={item.track} />
})}
</div>
</div>
)
}
export default Body
Here is the Songs component
import React from "react";
import './SongRow.css'
function Songs({ track }) {
console.log(track);
return (
<div className="songRow" >
<img className="songRow__album" src={track.album.images[0].url} alt="" />
<div className="songRow__info">
<h1>{track.name}</h1>
<p>
{track.artists.map((artist) => artist.name).join(", ")} -{" "}
{track.album.name}
</p>
</div>
</div>
);
}
export default Songs;
You are not returning anything inside the map
{recently_played?.tracks.items.map(item => {
return <Songs track={item.track} />;
})}
[or] use the shorthand version of arrow function
{recently_played?.tracks.items.map(item => <Songs track={item.track} />)}

How can I use nested routes with props for a child component

I'm building an react app where I have a feed component and the feed component consists of array of post components. The post component contains a link in it for viewing the full post component. I'm not able to pass the respective props to the full post component. I'm not able to do a nested route for the fullpost component.
this is my layout component
import React, { Component } from "react";
import Header from "../Header/Header";
import classes from "./Layout.css";
import { Route, Switch } from "react-router-dom";
import FullPost from "../Feed/FullPost/FullPost";
import axios from "axios";
import Feed from "../Feed/Feed";
class Layout extends Component {
state = {
users: [],
};
componentDidMount() {
axios
.get("https://goodwill-60d8a.firebaseio.com/Users.json")
.then((response) => {
this.setState({ users: response.data });
});
}
render() {
console.log(this.state.users);
return (
<div className={classes.main}>
<div>
<Header />
</div>
<div className={classes.content}>
<Switch>
<Route
path="/"
exact
render={() => <Feed users={this.state.users} />}
/>
<Route path="/fullpost" exact render={() => <FullPost />} />
</Switch>
</div>
</div>
);
}
}
export default Layout;
FEED component
import React from "react";
import Post from "./Post/Post";
import classes from "./Feed.css";
const feed = (props) => {
const feedItems = Object.keys(props.users).map((key) => ({
id: key,
...props.users[key],
}));
return (
<div className={classes.feed}>
{feedItems.map((items) => (
<Post
key={items.id}
profilename={items.profileName}
profilepic={items.profilePic}
timestamp={items.timeStamp}
contentimage={items.contentImage}
contenttext={items.contentText}
trend={items.trend}
></Post>
))}
</div>
);
};
export default feed;
Post component
import React from "react";
import classes from "./Post.css";
import ShareButton from "../../UI/ShareButton/ShareButton";
import { Link } from "react-router-dom";
const post = (props) => {
return (
<div className={classes.post}>
<div className={classes.header}>
<div className={classes.profileimage}>
<img className={classes.pic} src={props.profilepic} alt="" />
</div>
<div className={classes.name}>{props.profilename}</div>
<div className={classes.timestamp}>{props.timestamp}</div>
</div>
<div className={classes.container}>
<div className={classes.image}>
<img src={props.contentimage} alt="" />
</div>
<div>
<div className={classes.text}>
<span>{props.contenttext}</span>
</div>
<div className={classes.fullpost}>
<Link to="/fullpost" {...props}>
See Full Post
</Link>
</div>
</div>
</div>
<div className={classes.footer}>
<div className={classes.trend}>
<span>{props.trend}</span>
</div>
<ShareButton />
</div>
</div>
);
};
export default post;
Full Post component
import React from "react";
import classes from "./FullPost.css";
import pic from "../../../Assets/Images/self.jpg";
import { Link } from "react-router-dom";
const fullPost = (props) => {
return (
<div className={classes.fullpost_container}>
<div className={classes.photo_container}>
<img src={props.profilepic} alt=" " />
</div>
<div className={classes.sidebar}>
<div className={classes.profileimage}>
<img src={props.profilePic} alt="" />
</div>
<div className={classes.profilename}>Tony Kroos</div>
<div className={classes.timestamp}>3 Hours Ago</div>
</div>
<div className={classes.feedlink}>
<Link to="/" className={classes.feedlink_text}>
See more posts
</Link>
</div>
</div>
);
};
export default fullPost;

Can't get a react component to render using routing

I am new to react and I'm trying to render a component called {Chat} in a container using routing, but it doesn't give any output (or errors). Here's my code:
import React from "react";
import { Link } from "react-router-dom";
import Axios, { baseURL } from "../../services/config";
import "./Join.css";
import convIcon from "../../assets/selectIcon.png";
import Chat from "../Chat/Chat";
render() {
const { name, room, groups } = this.state;
const { match } = this.props;
const groupsList =
groups.length > 0 &&
groups.map(group => {
return (
<Link className="chatLink" to={`${match.url}/joinChat/chat`}>
<div className="chatList">
<img src={convIcon} title="logo" className="chatIcon" alt="" />
<h2 className="groupName">
{group.name}
<span className="timestamp">2:30 PM</span>
</h2>
<span className="lastMsg">Last message text</span>
</div>
</Link>
);
});
return (
<div className="joinOuterContainer">
<div className="joinInnerContainer">
<h1 className="heading">Conversations</h1>
<div className="chatListContainer">{groupsList}</div>
</div>
<div>
<Route path={`${match.url}/joinChat/Chat`} component={Chat}/>
</div>
</div>
);
}

Categories