React webpage refreshing every 4-6 seconds - javascript

I'm not really sure even what part of my code to show because it's such a general error, but everytime I npm start my React webpage it automatically goes from the home page to the authentication dashboard and starts refreshing.
I'm guessing it's a problem with React Router but I'm not really sure about this either?
This is how my App.js App component currently looks, which has the main Route functionality.
const App = () => {
const [auth, setAuth] = useState(false);
useEffect(() => {
localStorage.setItem("user", auth);
}, [auth]);
return (
<div className="landing" style={{zIndex:0, margin:"0px", position:"fixed"}}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
{!auth && (
<Route
path="/auth"
element={
<Auth authenticate={(val) => setAuth(val === 1 ? true : false)} />
}
/>
)}
{auth && (
<>
<Route path="/dashboard" element={<Dashboard />} />
</>
)}
<Route
path="*"
element={<Navigate to={auth ? "/dashboard" : "/auth"} />}
/>
</Routes>
</div>
);
}
And this is how my Home.js Home component file looks like
function Home() {
return (
<div className="main">
<div className="landingImageDiv">
<img src={ligaLogo} alt="uchisvg" className="landingImage" />
<div id="fade" className="linkDiv topMargin5">
<div>
<Link to="/about" className="popupLink">
<span className="hover">[About]</span>
</Link>
</div>
<div>
<Link to="/auth" className="popupLink">
<span className="hover">[Talent Network]</span>
</Link>
</div>
<div>
{/* Format to request access to platform */}
<a href="https://forms.gle/vKzq5M9n56oKKV5DA" className="popupLink">
<span className="hover">[Request RSO Onboarding]</span>
</a>
</div>
</div>
</div>
<div className="landing" id="fade">
<div style={{ zIndex: 5, position: "relative" }}></div>
</div>
</div>
);
}

Change your route definition as follows:
{
!auth ? (
<Route
path="/auth"
element={
<Auth authenticate={(val) => setAuth(val === 1 ? true : false)} />
}
/>
) : (
<>
<Route path="/dashboard" element={<Dashboard />} />
</>
);
}

Related

Como llevar el valor de un estado de un componente a otro?

I have this navbar component and it contains a "darkmode" icon, which executes a "useState function to change the icon from light to dark, adding an "active" class, and I would like to carry that same "darkModeToggle" value to the initial component in "App" to add a "dark" to the layout class.
export default function Navbar() {
const [darkModeToggle, setDarkModeToggle] = useState(false);
return (
<>
<header className='header'>
<div className='header__container'>
<div
className={
darkModeToggle
? 'header__container__darkmode active'
: 'header__container__darkmode'
}
onClick={() => {
setDarkModeToggle(!darkModeToggle);
}}
>
<BiSun className='sun' />
<BiMoon className='moon' />
</div>
</div>
</header>
</>
);
}
export default function App() {
return (
<div className='layout'>
<Navbar />
<Routes>
<Route path='/' element={<Home />} />
<Route path='/about' element={<About />} />
<Route path='/services' element={<Services />} />
<Route path='/contact' element={<Contact />} />
<Route path='*' element={<NotFound />} />
</Routes>
</div>
);
}
Put the state in the parent component in this case App and pass the prop throught Navbar
export default function App() {
const [darkModeToggle, setDarkModeToggle] = useState(false);
return (
<div className='layout'>
<Navbar darkModeToggle={darkModeToggle} setDarkModeToggle={setDarkModeToggle}/>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/about' element={<About />} />
<Route path='/services' element={<Services />} />
<Route path='/contact' element={<Contact />} />
<Route path='*' element={<NotFound />} />
</Routes>
</div>
);
}
and in the Navbar
function Navbar({darkModeToggle, setDarkModeToggle}) {
return (
<>
<header className="header">
<div className="header__container">
<div
className={
darkModeToggle
? "header__container__darkmode active"
: "header__container__darkmode"
}
onClick={() => {
setDarkModeToggle(!darkModeToggle);
}}
>
<BiSun className="sun" />
<BiMoon className="moon" />
</div>
</div>
</header>
</>
);
}

Unable to read attributes of props in React

I'm building a winery themed shopping app in React and I'm using functional components. I have 12 products (wines) displayed on one page, and I want to make a separate page for each wine when the user clicks on it.
This is how I handled routes:
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/products" element={<Products wines={products}/>} />
<Route path="/contact" element={<Contact />} />
<Route path="/cart" element={<Cart />} />
{wines.map((wine) => (
<Route key={wine.id} path={`/shop/${wine.id}`} element={<Item item={wine} />}/>
))}
</Routes>
</BrowserRouter>
I mapped through all of the wines and created a separate route for each of them, and sent a particular wine as a prop to each "Item" component.
Item component looks like this:
const Item = (item) => {
return (
<>
<Header />
<div className="item_container">
<img className="item_image" alt={item.name} src={item.image} />
<h1 className="item_name">{item.name}</h1>
<h3 className="item_price">{item.price}</h3>
</div>
<Footer />
</>
)
When I console log "item" in this component, I get the specific wine and I can see all of its attributes (name, price, image URL), but when I try to access those attributes in order to display them (item.name, item.image, item.price), the console logs "undefined".
How can i fix this?
You've passed a item prop to the Item component.
<Item item={wine} />
And then named the props object item in the Item component.
const Item = (item) => { ... }
Either rename to props and correctly access props.item.xxx
const Item = (props) => {
const { item } = props;
return (
<>
<Header />
<div className="item_container">
<img className="item_image" alt={item.name} src={item.image} />
<h1 className="item_name">{item.name}</h1>
<h3 className="item_price">{item.price}</h3>
</div>
<Footer />
</>
);
}
or destructure item directly
const Item = ({ item }) => (
<>
<Header />
<div className="item_container">
<img className="item_image" alt={item.name} src={item.image} />
<h1 className="item_name">{item.name}</h1>
<h3 className="item_price">{item.price}</h3>
</div>
<Footer />
</>
);
An optimization I'd suggest is to declare a single route with the wine id as a route path param, and then access the wines array in Item.
Example:
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/products" element={<Products wines={products}/>} />
<Route path="/contact" element={<Contact />} />
<Route path="/cart" element={<Cart />} />
<Route path="/shop/:wineId" element={<Item />} />
</Routes>
</BrowserRouter>
...
import { useParams } from 'react-router-dom';
const Item = () => {
const { wineId } = useParams();
const wine = wines.find(wine => wine.id === wineId);
if (!wine) return <div>No wine found.</div>;
return (
<>
<Header />
<div className="item_container">
<img className="item_image" alt={wine.name} src={wine.image} />
<h1 className="item_name">{wine.name}</h1>
<h3 className="item_price">{wine.price}</h3>
</div>
<Footer />
</>
);
}
Please check null and empty array for "wines" first , if not null then map through "wines"

After adding framer-motion, routing not works but link change

I added framer motion to my project, because i want to make some animations between pages, but now i've been staying all the time at the home page. I will be grateful for any help. Here's my code:
class App extends Component {
//(...)
location = () => {
useLocation();
}
//(...)
<Router>
<nav>
{!this.state.setIsAuth ? (
<>
<Link to="/">Home</Link>
<Link to="/contact">Contact</Link>
<Link to="/login"> Login </Link>
</>
) : (
<>
<Link to="/news"> News </Link>
<Link to="/createpost"> Create Post </Link>
<Link to="/calendar"> Calendar </Link>
<a href="/" onClick={this.signUserOut}> Log Out</a>
</>)}
</nav>
<AnimatePresence>
<Routes location={this.location} key={this.location.pathname}>
<Route exact path="/" element={<Home />} />
<Route path="/news" element={<News />} />
<Route path="/login" element={<Login setIsAuth={this.signIn} />} />
<Route path="/contact" element={<Contact />} />
<Route path="/createpost" element={<CreatePost setIsAuth={this.signIn} />} />
<Route path="/calendar" element={<Calendar />} />
</Routes>
</AnimatePresence>
</Router>
and Home.js to show you how structures of my pages look like
class Home extends Component {
render() {
return (
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
<header className="header">
<div className="header__text-box">
<h1 className="heading__text-box">
<span className="heading-primary--main">TeamWork</span>
<span className="heading-primary--sub">THE WAY TO SUCCESS</span>
</h1>
Take your opportunity
</div>
</header>
</motion.div>
)
}
}

No routes matching location "/dash/1"

I have the following problem. my route is not registered and i dont know why.
Links
dashboard.jsx
this code generates all the links.
<div className="flex w-3/4 m-auto flex-col mt-10 xl:w-1/2">
{questions.map(({ id, question }) => {
return (
<Link to={`/dash/${id}`}>
<QuestionHeader question={question} />
</Link>
);
})}
</div>
/dash/1,/dash/2,.... are generated by the map function above.
i have two files that represent the routes.
NavRoutes
const NavRoutes = () => {
return (
<Routes>
<Route path="/:id" element={<Question />} />
<Route path="" element={<Dashboard />} />
</Routes>
);
};
export default NavRoutes;
here is the Main component
const Main = () => {
return (
<div>
<NavBar />
<NavRoutes />
<Footer />
</div>
);
};
export default Main;
and the main routes for authentication and accessing the main page
const App = () => {
let { user } = useAuthContext();
return (
<div className="w-full bg-slate-700 block fixed h-full">
<Header />
<Router>
<Routes>
<Route
path="/dash"
element={!user ? <Navigate to="/auth" /> : <Main />}
>
</Route>
<Route path="" element={<Login />} />
</Routes>
</Router>
</div>
);
};
when i try to access /dash/1, i get the following error
router.ts:11 No routes matched location "/dash/1"
Did you try the following in your NavRoutes (prepending '/dash' to '/:id'):
<Route path="/dash/:id" element={<Question />} />
i solved this by doing the following
const App = () => {
let { user } = useAuthContext();
return (
<div className="w-full bg-slate-700 block fixed h-full">
<Header />
<Router>
<Routes>
<Route
path="/dash/*"
element={!user ? <Navigate to="/auth" /> : <Main />}
>
</Route>
<Route path="/auth" element={<Login />} />
</Routes>
</Router>
</div>
);
};
you need to include a * when nesting deeper

how to render same component in every route

import ...
const App = () => {
const [showModal, setShowModal] = useState(false);
const toggleModalShow = () => {
setShowModal(!showModal);
};
return (
<div className="app">
<Router>
<ScrollToTop>
<Routes>
<Route
exact
path="/"
element={
<>
<Header
toggleModalShow={toggleModalShow}
showModal={showModal}
/>
<main className="main">
<Home />
</main>
</>
}
/>
<Route
path="/games/:game"
element={
<>
<Header
toggleModalShow={toggleModalShow}
showModal={showModal}
/>
<GameLobby />
</>
}
/>
<Route
path="/games"
element={<PrivateRoute isLoggedIn={isLoggedIn} />}
>
<Route
path="/games"
element={
<>
<Header
toggleModalShow={toggleModalShow}
showModal={showModal}
/>
<Games />
</>
}
/>
</Route>
</Routes>
</ScrollToTop>
</Router>
</div>
);
};
export default App;
Hi all.i want to show <Header /> component in every route but to this i have to use <Header /> component in every <Route />. Is there any way to do that without ? Finally i would be appreciate if you give me feedback about project.
repo : https://github.com/UmutPalabiyik/mook
deploy: https://mook-f2b4e.web.app
for testing:
username: test
pass: 123
Just move the Header above Routes:
return (
<div className="app">
<Router>
<Header
toggleModalShow={toggleModalShow}
showModal={showModal}
/>
<ScrollToTop>
<Routes>
<Route
exact
path="/"
element={
<>
<main className="main">
<Home />
</main>
</>
}
/>
...
</Routes>
</ScrollToTop>
</Router>
</div>
);
};

Categories

Resources