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
/>
Related
// 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
Coding a project using React. It's been 3 days I've looking for a solution. I had been learning coding and trying to integrate stripe payment option on my web-app. However, unable to get the proper result. Searched a lot, found no solution.
Code is below :
App.js
import { Elements } from '#stripe/react-stripe-js';
import { loadStripe } from '#stripe/stripe-js';
import { useEffect } from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import './App.css';
import Checkout from './Checkout';
import { auth } from './firebase';
import Header from './Header';
import Home from './Home';
import Login from './Login';
import Payment from './Payment';
import { useStateValue } from './StateProvider';
const promise = loadStripe("pk_test_51KtYdQSJwVy1hdNxUPD5HK8KcKbLDVSic6q6jfdPxuSLYiCjuwzBfE8Eo5u0zVclLgPP33InVTjAyM4rZP3ouWB9009AL3lsZ6");
function App() {
const [{ }, dispatch] = useStateValue();
useEffect(() => {
auth.onAuthStateChanged(authUser => {
console.log("THE USER IS >>>>> ", authUser);
if (authUser) {
dispatch({
type: "SET_USER",
user: authUser
});
}
else {
dispatch({
type: "SET_USER",
user: null
})
}
})
}, []);
return (
<BrowserRouter>
<div className="App">
<Header />
{console.log("load stripe>>>>>>>>",promise)}
<Routes>
<Route path="/payment" element={
<Elements stripe={promise}>
<Payment />
</Elements>
} />
<Route path="/login" element={<Login />} />
<Route path="/checkout" element={<Checkout />} />
<Route path="/" element={<Home />} />
</Routes>
</div>
</BrowserRouter>
);
}
export default App;
Component in which using Stripe and CardElement (Payment.js) :
import { CardElement, useElements, useStripe } from "#stripe/react-stripe-js";
import React, { useState } from "react";
import CurrencyFormat from "react-currency-format";
import { Link } from "react-router-dom";
import CheckoutProduct from "./CheckoutProduct";
import "./Payment.css";
import { getBasketTotal } from "./reducer";
import { useStateValue } from "./StateProvider";
function Payment() {
const [{ basket, user }, dispatch] = useStateValue();
const stripe = useStripe();
const elements = useElements();
const [error,setError]=useState(null);
const [disabled,setDisabled]=useState(true);
const [succeeded,setSucceeded]=useState(false);
const [processing,setProcessing]=useState("");
const handleSubmit = event => {
//do all the stripe stuff
event.preventDefault();
}
const handleChange = event =>{
// Listen for changes in the CardElement
// and display any errors as the customer types card details
setDisabled(event.empty);
setError(event.error ? event.error.message : "");
}
return (
<div className="payment">
<div className="payment__container">
<h1>
Checkout ({<Link to="/checkout">{basket?.length} items</Link>})
</h1>
{/* Payment section - delivery address */}
<div className="payment__section">
<div className="payment__title">
<h3>Delivery Address</h3>
</div>
<div className="payment__address">
<p>{user?.email}</p>
<p>786 Chaurangi Marg</p>
<p>Delhi, India</p>
</div>
</div>
{/* Payment section - Review items */}
<div className="payment__section">
<div className="payment__title">
<h3>Review Items and Delivery</h3>
</div>
<div className="payment__items">
{basket.map(item =>
<CheckoutProduct
id={item.id}
title={item.title}
price={item.price}
rating={item.raing} />
)}
</div>
</div>
{/* Payment section - payment method */}
<div className="payment__section">
<div className="payment__title">
<h3>Payment Method</h3>
</div>
<div className="payment__details">
<form onSubmit={handleSubmit}>
{/*<CardElement />*/}
<div className="card__element">
<CardElement />
</div>
<div className="payment__priceContainer">
<CurrencyFormat
renderText={(value)=>(
<>
<h3>Order Total: {value}</h3>
</>
)}
decimalScale={2}
value={getBasketTotal(basket)}
displayType={"text"}
thousandSeparator={true}
prefix={"₹"}
/>
<button disabled={processing || disabled || succeeded}>
<span>{processing ? <p>Processing</p> : "Buy Now"}</span>
</button>
</div>
{error && <div>{error}</div> }
</form>
</div>
</div>
</div>
</div>
)
}
export default Payment;
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;
i'm trying to clone amazone website i'm following (celever programmer on youtube)
so i wanted to create amazon basket with React context api this error occurs "Error: Objects are not valid as a React child (found: object with keys {map, forEach, count, toArray, only}). If you meant to render a collection of children, use an array instead."
Here is my code
index.js :
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { StateProvider } from "./StateProvider";
import reducer, { initialState } from "./reducer";
ReactDOM.render(
<React.StrictMode>
<StateProvider initialState={initialState} reducer={reducer}>
<App />
</StateProvider>
</React.StrictMode>,
document.getElementById("root")
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
serviceWorker.unregister();
stateProvider.js:
import React, { createContext, useContext, useReducer } from "react";
import { Children } from "react";
export const StateContext = createContext();
export const StateProvider = ({ reducer, initialState, children }) => (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{Children}
</StateContext.Provider>
);
export const useStateValue = () => useContext(StateContext);
reducer.js:
export const initialState = {
basket: [],
};
function reducer(state, action) {
switch (action.type) {
case "ADD_TO__BASKET":
break;
case "REMOVE_FROM_BASKET":
break;
default:
return state;
}
}
export default reducer;
header.js:
import React from "react";
import "./Header.css";
import { Link } from "react-router-dom";
import SearchIcon from "#material-ui/icons/Search";
import { grey } from "#material-ui/core/colors";
import ShoppingBasketIcon from "#material-ui/icons/ShoppingBasket";
import { useStateValue } from "./StateProvider";
function Header() {
const [{ basket }] = useStateValue();
return (
<nav className="header">
{/* logo */}
<Link to="/">
<img
className="header__logo"
src="https://www.mabaya.com/wp-content/uploads/2019/10/amazon_PNG25.png"
alt=""
/>
</Link>
{/* SearchBox */}
<div className="header__search">
<input type="text" className="header__SearchBox" />
<SearchIcon className="header__SearchIcon" />
</div>
{/* Links */}
<div className="header__nav">
{/* 1link */}
<Link to="/login" className="header__link">
<div className="header__option">
<span className="header__optionsecondary">Hello,</span>
<span>Sign in</span>
</div>
</Link>
{/* 2link */}
<Link to="/check" className="header__link">
<div className="header__option">
<span className="header__optionsecondary">returns </span>
<span>& orders</span>
</div>
</Link>
{/* 3link */}
<Link to="/" className="header__link">
<div className="header__option">
<span className="header__optionsecondary">Your</span>
<span>Prime</span>
</div>
</Link>
{/* basket link */}
<Link to="/check" className="header__link">
<div className="header__optionbasket">
{/* shopping Basket Icon */}
<ShoppingBasketIcon style={{ color: grey[50] }} />
{/* Number of items in the basket */}
<span className="header__optionbaskettext"> {basket.length}</span>
</div>
</Link>
</div>
{/* panier */}
</nav>
);
}
export default Header;
App.js:
import "./App.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Header from "./Header";
import Home from "./Home";
import Login from "./Login";
function App() {
return (
<Router>
<div className="app">
<Switch>
<Route path="/login">
<Header />
<Login />
</Route>
<Route path="/check">
<Header />
<h1>check guys</h1>
</Route>
<Route path="/">
<Header />
<Home />
</Route>
</Switch>
</div>
</Router>
);
}
export default App;
Thank you in advance for your answer.
So I have a LoginPage that looks like this,
and when you login, you will be directed to this page:
now, I want my login page to don't have a navigation and look like this,
how can I do that?
so I have this, in my App.js
import React, { Component } from 'react';
import { Route } from 'react-router-dom';
import LoginPage from "./Login";
import Main from "./Main";
import Menu from "./Menu";
class App extends Component {
constructor(props){
super(props);
this.state={
loginPage:[],
uploadScreen:[]
}
}
render() {
return (
<div className="ui container">
<Route path="/" exact component={LoginPage} />
<Menu />
<Main />
</div>
);
}
}
export default App;
My Menu.js:
import React from 'react';
import { Link } from 'react-router-dom';
import {
Container,
Dropdown,
Menu,
} from 'semantic-ui-react';
const FixedMenuLayout = () => (
<div>
<Menu fixed='top' inverted>
<Container>
<Menu.Item as='a' header>
IRC
</Menu.Item>
<Menu.Item as={ Link } to= "/upload" >Create Material</Menu.Item>
<Menu.Item as={ Link } to= "/assign-material" >Assign Material</Menu.Item>
<Menu.Item as={ Link } to= "/create-group">Create Group</Menu.Item>
<Menu.Item as={ Link } to= "/assign-doctor">Assign Group</Menu.Item>
<hr />
<Dropdown item simple text='Name of Logged In User'>
<Dropdown.Menu>
<Dropdown.Item>Log Out</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</Container>
</Menu>
</div>
)
export default FixedMenuLayout
and my Main.js:
import React from 'react';
import { Route ,Switch } from 'react-router-dom';
import UploadScreen from "./UploadScreen";
import CreateGroup from "./CreateGroup";
import AssignDoctor from "./AssignDoctor";
import AssignMaterial from "./AssignMaterial";
const Main = () => (
<main>
<Switch>
<Route path="/upload" exact component={UploadScreen} />
<Route path="/assign-material" exact component={AssignMaterial} />
<Route path="/assign-doctor" exact component={AssignDoctor} />
<Route path="/create-group" exact component={CreateGroup} />
</Switch>
</main>
)
export default Main
I am new in ReactJS so please be considerate in answering and thank you for your time!
my App.js
render() {
const path = window.location.pathname;
return (
<div className="ui container">
<Route path="/" exact component={LoginPage} />
{path !== '/' &&
<div>
<Menu />
<Main />
</div>
}
</div>
);
}
and it works now :)