pass in props into component to render - javascript

// Warning: Cannot read properties of undefined (reading 'params')
// im try to get movie_id from movielist.js to view single movie on movie.js onclicking view review
// basically my error is from inability to pass the props into movie.js
//in nav/index.js
import { BrowserRouter as Router, Routes, Route, useParams} from "react-router-dom";
import Navbar from './navbar';
import MovieList from "../components/movie-list"
import Movie from "../components/movie"
const Nav = () => {
return (
<Router>
<Navbar/>
<Routes>
<Route exact path={'/'} element={<MovieList/>}/>
<Route path='/movies/:id/' element={<Movie props={useParams()} />} />
</Routes>
</Router>
)}
//in movielist.js
import React, {useState, useEffect} from 'react'
import MovieDataService from "../services/movie"
import { Link } from 'react-router-dom'
const MovieList = () => {
....
return (
<div>
....
<div>
{movies.map((movie)=>{
return(
<div className="card" key={movie._id}>
<div className="card-container">
<div className='card-img'>
<img src={movie.poster+"/100px180"} alt=""/>
</div>
<div className="card-body">
<h1>{movie.title}</h1>
<h2>Rating:{movie.rated}</h2>
<p>{movie.plot}</p>
<Link to={"/movies/"+movie._id}>View Review</Link>
</div>
</div>
</div>
);
})}
</div>
</div>
)
}
// in movie.js
import React, { useState, useEffect } from 'react'
import MovieDataService from '../services/movie'
import { Link } from 'react-router-dom'
const Movie = (props) => {
useEffect(()=>{
getMovie(props.match.params.id)
},[props.match.params.id]) //won't call getMovie Multiple times unless id is updated.
return (
<div>
<div className="card-container">
<div className='card-img'>
<img src={movie.poster+"/100px250"} alt=""/>
</div>
<div className="card-body">
<h1>{movie.title}</h1>
<p>{movie.plot}</p>
{props.user && <Link to={"/movies/"+props.match.params.id+"/review"}>Add Review</Link>
}
</div>
</div>
);
})}
</div>
</div>
)
}

Use useParams() hook to get url params.
const {id} = useParams()
useEffect(()=>{
getMovie(id)
},[id])
replace props.match.params.id with id everywhere

Related

how to connect two component when i click on submit button

I have some user components on which I used the navigation component and I am routing two components on it. when I click on the Device.js component button it should remove device.js and it should redirect to the Keyregister.js component which is having navigation component in it .It should change the value according to the props sent to it. But it is not happening.
user.js
import React from "react";
import { Route, Switch } from "react-router";
import "./User.css";
import Navigation from "./Dashboard/Navigation";
import AuthModel from "./Dashboard/AuthModel";
import DeviceDetails from "./Dashboard/DeviceDetails";
function User() {
return (
<>
<Navigation
link1={""}
link2={"Authmodel"}
link3={"Requests"}
link1name={"Key Status"}
link2name={"Key Upload"}
link3name={"KEY DOWNLOAD"}
/>
<Switch>
<Route path="/User/Dashboard/AuthModel" component={AuthModel} />
<Route path="/User/Dashboard/DeviceDetails" component={DeviceDetails} />
</Switch>
</>
);
}
export default User;
Navigation.js
import React from "react";
import "./Navigation.css";
import { Link } from "react-router-dom";
import { useHistory } from "react-router";
import { Image } from "react-bootstrap";
import EvoVert from "../../../Resources/EvoluteVert.png";
function Navigation(props) {
const history = useHistory();
const handleLogout = (e) => {
e.preventDefault();
localStorage.removeItem("accessToken");
localStorage.removeItem("roleType");
history.push("/");
};
return (
<>
<main classMain="main">
<aside className="sidebar ">
<Image className="Evo-logo" src={EvoVert} />
<nav className="nav">
<ul style={{ textDecoration: "none" }}>
<li>
<Link to={`/User/Dashboard/${props.link2}`}>
{props.link2name}
</Link>
</li>
<li>
<Link to={`/User/Dashboard/${props.link1}`}>
{props.link1name}
</Link>
</li>
<li>
<Link to={`/User/Dashboard/${props.link3}`}>
{props.link3name}
</Link>
</li>
</ul>
</nav>
</aside>
</main>
</>
);
}
export default Navigation;
Device.js
import React, { useState, useEffect } from "react";
import { Form } from "react-bootstrap";
import "./Dashboard.css";
import { useHistory } from "react-router";
import KeyRegister from "./KeyRegister";
function DeviceDetails() {
const history = useHistory();
const [visible, setvisible] = useState(true);
const [serialNum, setSerialNum] = useState("");
const [slot, setSlot] = useState("");
const frmsubmit = (e) => {};
return (
<>
<section className="device-Details_Dashboard">
<div className="container">
<div
className="heading"
style={{
color: "#312450",
fontWeight: "400",
fontSize: "35px",
padding: "1rem",
}}
>
DEVICE DETAILS
</div>
<Form onSubmit={frmsubmit}>
<div>
<div className="device-details-box">
<label>Serial Number</label>
<br />
<input
type="text"
value={serialNum}
onChange={(e) => setSerialNum(e.target.value)}
/>
</div>
<div className="device-details-box">
<label>Slot Number</label>
<br />
<input
type="text"
value={slot}
onChange={(e) => setSlot(e.target.value)}
/>
</div>
</div>
<button className="devDetSub" onClick={frmsubmit}>
<span>SUBMIT</span>
</button>
</Form>
</div>
</section>
{visible && <KeyRegister />}
</>
);
}
export default DeviceDetails;
KeyRegister.js
import React, { useState, useEffect } from "react";
import "./Navigation.css";
import { Route, Switch } from "react-router";
import DUPKT from "./DUPKT";
import MasterSession from "./MasterSession";
import AES from "./AES";
import Navigation from "./Navigation";
function KeyRegister() {
return (
<>
<Navigation
link1={"DUPKT"}
link2={"MasterSession"}
link3={"AES"}
link1name={"DUPKT"}
link2name={"MASTER KEY"}
link3name={"AES"}
/>
<main classMain="main">
<Switch>
<Route path="/User/Dashboard/DUPKT" component={DUPKT} exact />
<Route
path="/User/Dashboard/MasterSession"
component={MasterSession}
exact
/>
<Route path="/User/Dashboard/AES" component={AES} exact />
</Switch>
</main>
</>
);
}
export default KeyRegister;
I cannot see anywhere in your naviagation component props you are passing device details.
<Navigation
link1={""}
link2={"Authmodel"}
link3={"Requests"}
link1name={"Key Status"}
link2name={"Key Upload"}
link3name={"KEY DOWNLOAD"} //should have device details in props
/>

disappearance of a component after reloading the page

Everything works fine. Content changes after pressing NavLink, but when I reload the page, the content disappears. Аlthough, interestingly, the URL remains the same. How to fix, or so it should be?
*Before reloading *
*After reloading *
Code:
App.js:
import React from 'react'
import './App.css';
import Header from './components/Header/Header';
import Nav from './components/Nav/Nav';
import Profile from './components/Profile/Profile.jsx';
import Dialog from './components/Dialog/Dialog'
import { BrowserRouter, Route } from 'react-router-dom';
const App = () => {
return (
<BrowserRouter>
<div className="App">
<Header />
<Nav />
<Route path='/profile' component={Profile} />
<Route path='/dialog' component={Dialog} />
</div>
</BrowserRouter>
);
}
export default App;
Dialog.jsx:
import React from 'react'
import style from './Dialog.module.css'
import MessageOleg from '../Messages/MessageOleg'
import MessageMax from '../Messages/MessageMax'
import { BrowserRouter, Route, NavLink } from 'react-router-dom'
const Dialog = () => {
return (
<BrowserRouter>
<div className={style.dialog}>
<div className={style.users}>
<div className={style.user}> <NavLink to='/messageOleg'> Oleg </NavLink> </div><br />
<div className={style.user}> <NavLink to='/messageMax' >Max </NavLink> </div><br />
<div className={style.user}> Nata </div><br />
<div className={style.user}> Fuflo </div><br />
<div className={style.user}> Kiko </div><br />
</div>
<hr />
<Route path='/messageOleg' component={MessageOleg} />
<Route path='/messageMax' component={MessageMax} />
</div>
</BrowserRouter>
)
}
export default Dialog;
MessageOleg.jsx:
import React from 'react'
import style from './MessageOleg.module.css'
const MessageOleg = () => {
return (
<div className={style.messages}>
<div className={style.message}>
Hey
</div>
</div>
)
}
export default MessageOleg;

Router for specific component is not woking

I want to route specific component in other component but when I click on the link other components are disappeared
import React from 'react';
import { Route, Switch, BrowserRouter } from 'react-router-dom';
import Sidebar from '../componants/Sidebar'
import Navbar from '../componants/Navbar';
import Router from '../Routers/Routers'
import Answer from './Answer';
import Feed from './Feed'
const Layuot = () => {
return (
<>
<div className="container-fluid">
<Navbar />
<div className="rows row">
<div className='col-3'>
<Sidebar/>
</div>
<div className="col-9 ">
<div className="content">
<Switch>
<Route path='/feed'><Feed/></Route>
<Route path = '/answer/:q_id'><Answer/></Route>
</Switch>
</div>
</div>
</div>
</div>
</>
)
}
export default Layuot;
see output
enter image description here
See Url
enter image description here
Every component are disappeared and Feed component not ms

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;

Categories