REACT JS, component not rendering when saving except dashboard - javascript

I don't know why my other component is not rendering when I press save, except Dashboard. When I re-run rpm run dev the component is not working, it's rendering and saving. I want to real-time when I save code.
Here is the dashboard when I press save, it's rendering the text:
import React from "react"
export default function Dashboard() {
return <div>admin dashboard test rendering</div>
}
Here is the component not rendering and not saving when I save:
import React from "react"
export default function Profile() {
return <div> not rendering when i save Profile test</div>
}
Here is my router
import { createBrowserRouter } from 'react-router-dom'
import NotFound from './NotFound'
import AdminLayout from './components/AdminLayout'
import Dashboard from './views/admin/dashboard'
import Profile from './views/admin/Profile'
const router = createBrowserRouter([
{
path: '/admin',
element: <AdminLayout />,
children: [
{
path: '/admin/dashboard',
element: <Dashboard />
},
{
path: '/admin/profile',
element: <Profile />
},
]
},
{
path: '/*',
element: <NotFound />
}
])
Here is my parent route adminlayout
import { Navigate, Outlet, NavLink } from "react-router-dom"
import { useStateContext } from "../contexts/ContextProvider"
import axiosClient from "../axios-client"
export default function AdminLayout() {
const { setToken, setUser } = useStateContext()
function onLogOut() {
axiosClient.post('/logout').
then(() => {
setUser({})
setToken(null)
})
}
return (
<div id="defaultLayout">
<aside>
<NavLink to="/admin/dashboard">Dashboard</NavLink>
<NavLink to="/admin/profile">Profile</NavLink>
<NavLink to="/" onClick={onLogOut}>Logout</NavLink>
</aside>
<div className="content">
<header>
<div>header</div>
</header>
<main>
<Outlet />
</main>
</div>
</div>
)
}
I don't know what is the problem of my code maybe Vite or I coded the wrong code.

Related

React 6.4.0 common header for all the router

I am starting react project with react-router-dom version 6.4.0, but not able to create common header for all the routes.
App.js - This is the file where I am adding RouterProvider
import logo from './logo.svg';
import './App.css';
import { Link, Outlet, RouterProvider } from "react-router-dom";
import { routers } from "./routes/routes";
function App() {
return (
<RouterProvider router={routers}>
<div>Header</div>
<Outlet />
</RouterProvider>
);
}
export default App;
routes.js - In this file I am going to create all the routes
import { createBrowserRouter, redirect } from "react-router-dom";
import About from "../pages/About/About";
import Home from "../pages/Home/Home";
import { getUser, isAuthenticated } from "../sso/authUtil";
const authLoader = () => {
if (!isAuthenticated()) {
return redirect("https://google.com");
} else {
return getUser();
}
};
export const routers = createBrowserRouter([
{
path: "/",
element: <Home />,
loader: authLoader,
},
{
path: "/about",
element: <About />,
},
]);
Home.js - This file is home page which will have the links to other pages along with header
import React from "react";
import { Link, Outlet, useLoaderData } from "react-router-dom";
const Home = () => {
const loaderData = useLoaderData();
return (
<>
<div>Header</div>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<div>Home: {loaderData}</div>{" "}
<Outlet />
</>
);
}
export default Home;
About.js - It is normal component which say about
import React from "react";
const About = () => {
return <div>About</div>;
};
export default About;
I want both Home and About component to be loaded with header on top.
Even in react-router-dom#6.4.0 rendering layout routes with common UI still works the same.
Create a layout route component that render the common header component and an Outlet for nested routes.
Example:
const Layout = () => (
<>
<CommonHeader />
<Outlet />
</>
);
Import and render Layout on a layout route in the configuration.
const routers = createBrowserRouter([
{
element: <Layout />,
children: [
{
path: "/",
element: <Home />,
loader: authLoader
},
{
path: "/about",
element: <About />
}
]
}
]);
...
function App() {
return <RouterProvider router={routers} />;
}

react-router-dom#6.4.1 not rendering components and also not logging any errors

react-router-dom#6.4.1 is not rendering components.
I haven't coded React in a while now. I am trying to utilize react-router but something seems to be wrong. There's no error emitted but the components won't render. So many updates to react-router, it tough to keep up with.
Link to github repo
This is a sample of my root file.
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './app/store';
import './index.css';
import {
createBrowserRouter,
RouterProvider,
Route,
} from "react-router-dom";
import { Calendar, Message, Settings, Team } from './components';
import ErrorPage from "./error-page";
import Aside from './root';
const router = createBrowserRouter([
{
path: "/",
element: <Aside />,
errorElement: <ErrorPage />,
children: [
{
path: "/messages",
element: <Message />
},
{
path: "/team-members",
element: <Team />
},
{
path: "/calendar",
element: <Calendar />
},
{
path: "/settings",
element: <Settings />
}
]
}
]);
const container = document.getElementById('root')!;
const root = createRoot(container);
root.render(
<React.StrictMode>
<Provider store={store}>
<RouterProvider router={router} />
</Provider>
</React.StrictMode>
);
Check your CSS layout, your components are rendered, but they are at the bottom of the page.
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Outlet />
</div>
);
}
You can read it from here:
https://reactrouter.com/en/main/components/outlet
Today I faced the same trouble and here is solution:
Go to your main Container, where you want to see children.
then
import { Link, Outlet } from 'react-router-dom';
then
inser <Outlet /> component, in <div> where you want to render items.
Your code: If you want to render <Team/> you should import <Outlet/> to component where you want to see <Team/>.
import React from 'react';
import { Link, Outlet } from 'react-router-dom';
const Aside = () => {
return (
<div>
Welcome to Your personal gym
<Link to='/login'>Log In</Link>
<Link to='/registration'>Sign In</Link>
<Outlet/>
</div>
);
}
export default Aside;

Problem using useRoutes when redirecting with params

I am trying to set up my project for the first time using useRoutes and lazy loading with children. But I am having a problem that it won't load the children when redirected to that site? The Home page works perfectly fine.
https://codesandbox.io/s/great-rgb-ippuob?file=/src/Page/Home/index.js
Home path="/"
import React from "react";
import { Link } from "react-router-dom";
const Home = () => {
return (
<>
<h1>Hello Welcome to my beauty page</h1>
<Link to="/1">click me</Link>
</>
);
};
export default Home;
Children:
import React from "react";
import { useParams } from "react-router-dom";
const Id = () => {
const { id: loadingId } = useParams();
return <h1>Right now you are on the side of: {loadingId}</h1>;
};
export default Id;
App.js:
import "./styles.css";
import Route from "./Routes";
import { Suspense } from "react";
export default function App() {
return (
<>
<div className="App">
<Suspense fallback={<p>Loading...</p>}>
<Route />
</Suspense>
</div>
</>
);
}
Routes:
import { useRoutes } from "react-router-dom";
import React from "react";
export default function Router() {
return useRoutes([
{
path: "/",
element: <Home />,
children: [{ path: "/:id", element: <Id /> }]
}
]);
}
const Home = React.lazy(() => import("./Page/Home"));
const Id = React.lazy(() => import("./Page/Id"));
And in Index I have
<BrowserRouter>
<App />
</BrowserRouter>
You should add <Outlet /> in Layout/Parent component (Home for you)
const Home = () => {
return (
<>
<h1>Hello Welcome to my beauty page</h1>
<Link to="/1">click me</Link>
<Outlet />
</>
);
};
export default Home;

How to clear the screen before rendering

Seeing issues while developing a real time wallboard using react . I am displaying 2 components one after another Dashboard1( a table with data), Dashboard2(another table with data) with 3 secs time interval. My parent component is Dashboard it connects to my firestore DB to receive real-time updates and sends this data to Dashboard1 component and then Dashboard 1 renders its data and after 3 seconds calls Dashboard2 with the same data passed to it by Dashboard using props.history.push().I am seeing 2 issues here. The component Dashboard 2 is always rendered above Dashboard1.Like when i scroll down the page ,i can still see Dashboard1 at the bottom. How to clear off the page before rendering Dashboard1 and 2 .So that i just see a single component at a time on the screen.Below is my code for App, Dashboard ,Dashboard1 and Dashboard2.I am also seeing Dashboard 2 is being rendered multiple times in the console logs.
Kindly help me to fix these 2 issues:
App.js:
import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom'
import Dashboard from './components/Dashboard'
import Dashboard1 from './components/Dashboard1'
import Dashboard2 from './components/Dashboard2'
class App extends Component {
render() {
console.log('App')
return (
<BrowserRouter>
<div className="App">
<Route exact path='/' component={Dashboard} />
<Route exact path='/Dashboard1' component={Dashboard1} />
<Route exact path='/Dashboard2' component={Dashboard2} />
<Dashboard />
</div>
</BrowserRouter>
)
}
}
export default(App)
Dashboard.js:
import React, { Component } from 'react';
import { BrowserRouter, Route, Redirect } from 'react-router-dom'
import Dashboard1 from './Dashboard1'
import Dashboard2 from './Dashboard2'
import { connect } from 'react-redux'
import { firestoreConnect } from 'react-redux-firebase'
import { compose } from 'redux'
class Dasboard extends Component {
render() {
console.log('Dashboard')
const { agents } = this.props
if (!agents) {
return null
}
return (
<Dashboard1 data={agents}/>
)
}
}
const mapStateToProps = (state) => {
return {
agents: state.firestore.data.agent_groups
}
}
export default compose(
connect(mapStateToProps),
firestoreConnect([
{ collection: 'agent_groups' }
])
)(Dasboard)
Dashboard1.js:
import React from 'react'
import Table from '../layouts/Table'
import { withRouter } from 'react-router-dom'
const Dashboard1 = (props) => {
console.log('Dashboard1')
setTimeout(() => {
props.history.push({
pathname: '/Dashboard2',
state: { data: props.data.WFM_Inbound_Sales.agents }})
}, 3000);
return (
<div className="dashboard1">
<Table
data={props.data.WFM_Inbound_Sales.agents}
headers={[
{
name: 'Agent',
prop: 'name'
},
{
name: 'Total calls',
prop: 'InboundCalls'
}
]}
/>
</div>
)
}
export default withRouter(Dashboard1)
Dashboard2.js:
import React from 'react'
import Table from '../layouts/Table'
import { withRouter } from 'react-router-dom'
const Dashboard2 = (props) => {
console.log('Dashboard2')
setTimeout(() => {
props.history.push('/')
}, 3000);
return (
<div className="dashboard2">
<Table
data={props.location.state.data}
headers={[
{
name: 'Agent',
prop: 'name'
},
{
name: 'Status',
prop: 'state'
},
{
name: 'Time in status',
prop: 'TimeInCurrentState'
}
]}
/>
</div>
)
}
export default withRouter(Dashboard2)
You need to use switch which will render only one route of the given set like this
class App extends Component {
render() {
console.log('App')
return (
<BrowserRouter>
<div className="App">
<Switch>
<Route exact path='/' component={Dashboard} />
<Route exact path='/Dashboard1' component={Dashboard1} />
<Route exact path='/Dashboard2' component={Dashboard2} />
</Switch>
<Dashboard />
</div>
</BrowserRouter>
)
}
}
Check the doc here

Testing using Jest and Enzyme: how to navigate React Router DOM

I am trying to write an integration test for a React app created as part of a Udemy course. The app is using react-router-dom, and I want to simulate clicking on a Link, which should change the route, and then test something on the screen corresponding to the new route.
I was able to mount the App component using Enzyme, but I can't seem to navigate successfully in the test environment:
import React from 'react'
import { mount } from 'enzyme'
import { MemoryRouter } from 'react-router-dom'
import Root from 'src/Root'
import App from 'src/components/App'
it('navigates to the post screen when clicking the post button', () => {
const wrapped = mount(
// My Root component wraps the children with a Redux Provider
<Root initialState={{ auth: true }}>
<MemoryRouter>
<App />
</MemoryRouter>
</Root>
)
// Click on the post button
wrapped.find('a.post-link').simulate('click')
// Update the component, hoping that the navigation would take effect
wrapped.update()
// Expecting to find a CommentBox, which is what is rendered by the '/post' Route
// Unfortunately, it seems that the navigation either didn't occur or is still ongoing, as the test fails: there are 0 CommentBox components found.
expect(wrapped.find('CommentBox').length).toEqual(1)
})
This is my App component, for reference:
import React, { Component } from 'react'
import { Link, Route } from 'react-router-dom'
import { connect } from 'react-redux'
import CommentBox from 'src/components/CommentBox'
import CommentList from 'src/components/CommentList'
import * as actions from 'src/actions'
class App extends Component {
renderButton() {
const { auth, changeAuth } = this.props
return (
<button
onClick={() => changeAuth(!auth)}
className="auth-button"
>
Sign {auth ? 'out' : 'in'}
</button>
)
}
renderHeader() {
return (
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link className="post-link" to="/post">Post a comment</Link>
</li>
<li>
{this.renderButton()}
</li>
</ul>
)
}
render() {
return (
<div>
{this.renderHeader()}
<Route path="/post" component={CommentBox} />
<Route path="/" exact component={CommentList} />
</div>
)
}
}
function mapStateToProps(state) {
return { auth: state.auth }
}
export default connect(mapStateToProps, actions)(App)

Categories

Resources