Unable to show Sidebar when add 2nd Route with index element - css

I am developing a dropdown Sidebar with ReactJS, and using separate files with the name of sizeConfig and colorConfigs and access it in mainLayout page using material UI.
sizeConfigs.js:
const sizeConfigs = {
sidebar:{
width:"300px"
}
}
export default sizeConfigs
colorConfigs.js:
import { colors } from "#mui/material";
const colorConfigs = {
sidebar: {
bg: "#233044",
color: "#eeeeee",
hoverBg: "#1e293a",
activeBg: "#1e253a"
},
topbar: {
bg: "#fff",
color: "#000"
},
mainBg: colors.grey["100"]
};
export default colorConfigs;
MainLayout.jsx:
import { Box, Toolbar } from '#mui/material'
import React from 'react'
import Topbar from '../common/Topbar'
import sizeConfigs from '../../configs/sizeConfigs'
import colorConfigs from '../../configs/colorConfigs'
import Sidebar from '../common/Sidebar'
import { Outlet } from 'react-router-dom'
const MainLayout = () => {
return (
<Box sx={{display:"flex"}}>
<Topbar />
{/*2nd Box*/}
<Box componenet="nav" sx={{
width:sizeConfigs.sidebar.width,
flexShrink:0
}}>
<Sidebar />
</Box>
{/*3rd Box*/}
<Box component="main" sx={{
flexGrow:1,
p:3,
width:`calc(100%-${sizeConfigs.sidebar.width})`,
minHeight: "100vh",
backgroundColor:colorConfigs.mainBg
}}>
<Toolbar />
<Outlet />
</Box>
</Box>
);
};
export default MainLayout
App.jsx File:
import {BrowserRouter,Routes,Route} from 'react-router-dom'
import MainLayout from './components/layout/MainLayout';
//import HomePage from './pages/home/HomePage';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path='/' element={<MainLayout/>}/>
</Routes>
</BrowserRouter>
);
}
export default App;
This code is showing my sidebar with main page, but when I add 2nd Route with index element, only homepage is showing on my main screen sidebar is not showing.
Code after adding 2nd Route:
import {BrowserRouter,Routes,Route} from 'react-router-dom'
import MainLayout from './components/layout/MainLayout';
import HomePage from './pages/home/HomePage';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path='/' element={<MainLayout/>}/>
<Route index element={<HomePage/>}/>
</Routes>
</BrowserRouter>
);
}
export default App;
Please help me finding the mistake why my code is not displaying the sidebar and home page with display:flex as shown in the image:

Related

How to Override the style of Layout component in React?

I am using Next.js with Material-UI as the framework.
I have Layout component that wraps the contents with Material-UI <Container>.
I would like to override the style of Layout that limits the width of background, so that the background would extend to the full screen.
components/Layout.js
import { Container } from '#material-ui/core';
export default function Layout({ children }) {
return <Container>{children}</Container>;
}
pages/_app.js
import Layout from '../components/Layout';
...
<Layout>
<Component {...pageProps} />
</Layout>
...
pages/index.js
export default function App() {
return (
<div style={{ backgroundColor: "yellow" }}>
Home Page
</div>
)
}
Using Layout component comes in handy in most cases but sometimes I do want to override the certain styles of Layout from the child component.
In this case, how do I override the style of Layout component that puts the limit on maxWidth?
I tried to add {width: '100vw'} inside the style of pages/index.js, but did not work.
Any help would be appreciated.
Link to the SandBox
Using React Context is how I've solved this issue.
context/ContainerContext.js
import React from 'react';
const ContainerContext = React.createContext();
export default ContainerContext;
components/Layout.js
import React, { useState } from 'react';
import { Container } from '#material-ui/core';
import ContainerContext from '../context/ContainerContext';
export default function Layout({ children }) {
const [hasContainer, setHasContainer] = useState(true);
const Wrapper = hasContainer ? Container : React.Fragment;
return (
<ContainerContext.Provider value={{ hasContainer, setHasContainer }}>
<Wrapper>{children}</Wrapper>
</ContainerContext.Provider>
);
}
pages/index.js
import { useContext, useLayoutEffect } from 'react';
import ContainerContext from '../context/ContainerContext';
export default function App() {
const { setHasContainer } = useContext(ContainerContext);
// Where the magic happens!
useLayoutEffect(() => {
setHasContainer(false);
}, []);
return (
<div style={{ backgroundColor: "yellow" }}>
Home Page
</div>
);
}

How to display navbar when scrolled with WayPoint

so i'm trying to make my Navbar fixed to the top of the screen when i have scrolled below the actual Navbar. I am using WayPoints onEnter and onLeave to trigger when i have scrolled past. The issue i'm having is, that when styled is equal to false, the {position:'relative'} i believe makes the site crash and i'm not sure why, or what solution is.
import React, { useEffect, useState } from 'react'
import Navbar from './Navbar'
import { Box, Grid, Card, CardMedia, CardActionArea, Typography, CardContent, CardActions, Button }
from '#material-ui/core'
import Styles from './Styles'
import { Random } from 'react-animated-text'
import { projectSections } from './ListItems'
import { Waypoint } from 'react-waypoint';
const Portfolio = () => {
const [styled, setStyled] = useState(false)
const style = () => (
styled==false
? {
position:'fixed',
width:'100%',
zIndex:99
}
: {position:'relative'}
)
const handleWaypointEnter = () => (
setStyled(!styled) )
const handleWaypointLeave = () => (
setStyled(!styled)
)
return (
<>
<Waypoint
onEnter={handleWaypointEnter}
onLeave={handleWaypointLeave}
>
<div style={style()}>
<Navbar/>
</div>
</Waypoint>
{/* Ignore this for now
<Box style={{position:'relative'}}>
<Box component='div'>
<Typography align='center' className={classes.portTitle}>
<Random
className={classes.portTitle}
text="PORTFOLIO"
effect='pop'
effectChange={.8}
effectDuration={1.3}
/>
</Typography>
<Grid container justify='center' alignItems='center' style={{padding:20}}>
{project()}
</Grid>
</Box>
</Box>
*/}
</>
)
}
Have you tried with return statement in style function.

How to pass navigation props in React native in Stack Navigation?

I am new to react native and facing some issues with React Navigation version 5.x
App.js file is below
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import MyDrawer from "./components/MyDrawer";
import LoginScreen from "./screens/LoginScreen";
import firebase from "firebase";
import { firebaseConfig } from "./config";
firebase.initializeApp(firebaseConfig);
const Stack = createStackNavigator();
export default class App extends React.Component {
state = {
isLoggedIn: false,
};
logOut = () => {
this.setState({ isLoggedIn: false });
firebase.auth().signOut();
};
render() {
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false,
}}
>
{this.state.isLoggedIn ? (
<>
<Stack.Screen name="Home" component={MyDrawer} />
</>
) : (
<Stack.Screen name="SignIn" component={LoginScreen} />
)}
</Stack.Navigator>
</NavigationContainer>
);
}
}
If the user is logged in to firebase it will navigate to MyDrawer.js. It has a custom drawer and the drawer has a log out button.
MyDrawer.js
import HomeScreen from "../screens/HomeScreen";
import Colors from "../Colors";
import ShareListScreen from "../screens/ShareListScreen";
import Inpiration from "../screens/Inspiration";
const Drawer = createDrawerNavigator();
export default class MyDrawer extends React.Component {
state = {
title: this.props,
};
render() {
return (
<Drawer.Navigator
initialRouteName="Home"
drawerContent={(props) => <CustomDrawerContent {...props} />}
>
<Drawer.Screen name="Home" component={HomeScreen} />
<Drawer.Screen name="Share List" component={ShareListScreen} />
<Drawer.Screen name="Inspiration" component={Inpiration} />
</Drawer.Navigator>
);
}
}
function CustomDrawerContent(props) {
return (
<DrawerContentScrollView {...props}>
<View >
<ImageBackground source={image} >
<Text>
Bring
<Text>Me</Text>
</Text>
</ImageBackground>
</View>
<DrawerItemList {...props} />
<ImageBackground source={home} >
<Text >Home</Text>
</ImageBackground>
<ImageBackground source={work} >
<Text>Workplace</Text>
</ImageBackground>
<DrawerItem
label="Log out"
onPress={() => {
this.props.logOut;
this.props.navigation.navigate("SignIn");
// Once the button pressed I want the user to sign out from firebase and navigate
to the root and set isLoggedIn state to true in App.js.
}}
/>
</DrawerContentScrollView>
);
}
Once the logout button pressed I want the user to sign out from firebase and navigate to the root and set isLoggedIn state to true in App.js. ( Call the log out function in App.js).
How can I achieve this?
You can use the initialParams to pass the logout function.
<Stack.Screen name="Home" component={MyDrawer} initialParams={{this.logout}}/>
This function can be accessed in MyDrawer class as this.props.routes.params.logout()
And you dont have to navigate to signIn again as the state change happens you render the 'SignIn' so app will show the signin screen automatically.

How to change background color of active Navigation Tab?

I have Navigation Tab of material-ui used for my React Project.The selected active Tab must have background color and then switch back to original color when not active.The transparent is applied to both tabs and not the selected active tabs in the below code.I want to apply some background color for active tabs only. Any solution?
Here is the code for Navigation Tab
import React from 'react';
import PropTypes from 'prop-types';
import SwipeableViews from 'react-swipeable-views';
import { makeStyles, useTheme } from '#material-ui/core/styles';
import AppBar from '#material-ui/core/AppBar';
import Tabs from '#material-ui/core/Tabs';
import Tab from '#material-ui/core/Tab';
import Typography from '#material-ui/core/Typography';
import Box from '#material-ui/core/Box';
import ForecastDays from '../forecast/index';
const TabPanel = (props) => {
const { children, value, index, ...other } = props;
return (
<Typography
component="div"
role="tabpanel"
hidden={value !== index}
id={`full-width-tabpanel-${index}`}
aria-labelledby={`full-width-tab-${index}`}
{...other}
>
<Box p={3}>{children}</Box>
</Typography>
);
}
TabPanel.propTypes = {
children: PropTypes.node,
index: PropTypes.any.isRequired,
value: PropTypes.any.isRequired,
};
const a11yProps = (index) => {
return {
id: `full-width-tab-${index}`,
'aria-controls': `full-width-tabpanel-${index}`
};
}
const useStyles = makeStyles(theme => ({
root: {
backgroundColor: 'none',
width: 275,
marginLeft:72,
marginTop:40
},
}));
const DailyHourly = (props) => {
const classes = useStyles();
const theme = useTheme();
const [value, setValue] = React.useState(0);
const handleChange = (event, newValue) => {
setValue(newValue);
};
const handleChangeIndex = index => {
setValue(index);
};
const {forecastdays, hourlyforecast} = props
return (
<div className={classes.root}>
<AppBar position="static" color="default" style={{background: 'transparent'}}>
<Tabs
value={value}
onChange={handleChange}
indicatorColor="secondary"
textColor="primary"
variant="fullWidth"
aria-label="full width tabs example"
>
<Tab label="Daily" {...a11yProps(0)}
/>
<Tab label="Hourly" {...a11yProps(1)}
/>
</Tabs>
</AppBar>
<SwipeableViews
axis={theme.direction === 'rtl' ? 'x-reverse' : 'x'}
index={value}
onChangeIndex={handleChangeIndex}
>
<TabPanel value={value} index={0} dir={theme.direction}>
<ForecastDays forecastdays={forecastdays}/>
</TabPanel>
<TabPanel value={value} index={1} dir={theme.direction}>
<ForecastDays hourlyforecast={hourlyforecast}/>
</TabPanel>
</SwipeableViews>
</div>
);
}
export default DailyHourly
Watch out images for reference below.
Any suggestions highly appreciated... Thanks in advance
You can add a class based on the current active tab value. Something like below. You may have to create another function , if you don't know the number of tabs beforehand.
<Tab className={value === 0 ? classes.active : ""} label="Daily" {...a11yProps(0)}
/>
<Tab className={value === 1 ? classes.active : ""} label="Hourly" {...a11yProps(1)}
/>
Codesandbox - https://codesandbox.io/s/pedantic-ives-t7sir

ReactCSSTransitionGroup leave animation not applying to Route

Entering animations are applied correctly. Component seems to unmount prior to applying any leave, leave-active classes.
componentWillMount() {
this.setState({
routes: [(<Route exact path='/' component={HomeView}/>),
(<Route exact path='/account' component={YourAccountView}/>),
(<Route exact path='/settings' component={SettingsView}/>),
(<Route exact path='/about' component={AboutView}/>),
(<Route exact path='/machine/:_id' component={MachineDetailView}/>),
(<Route exact path='/floorview' component={FloorView}/>)]
})
}
render() {
return (
<div>
<NavBar/>
<div style={{position: 'relative', flexGrow: 1 , marginTop:40+'px'}}>
<ReactCSSTransitionGroup
transitionName="pageSlider"
transitionEnter={true}
transitionLeave={true}
transitionEnterTimeout={500}
transitionLeaveTimeout={500}>
{this.state.routes
.filter((e)=> e.props.path===this.context.router.history.location.pathname )
.map((e)=> React.cloneElement(e, { key: this.context.router.history.location.pathname} ))}
</ReactCSSTransitionGroup>
</div>
</div>
);
}
I can't tell if this is a ReactCSSTransitionGroup thing, or a React-Router v4 mounting/unmounting thing. Has anyone run into and solved similar issue?
this case works:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Route} from 'react-router-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<BrowserRouter>
<Route path="/" component={App}/>
</BrowserRouter>
,
document.getElementById('root')
);
App.js
import React, { Component } from 'react';
import { Switch, Route, Link } from 'react-router-dom';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import './App.css';
const One = ({match}) => (
<h2>{match.url}</h2>
)
const Two = ({match}) => (
<h2>{match.url}</h2>
)
const Three = ({match}) => (
<h2>{match.url}</h2>
)
const Four = ({match}) => (
<h2>{match.url}</h2>
)
const MyNav = () => (
<div>
<Link to='/One'>One</Link>
<Link to='/Two'>Two</Link>
<Link to='/Three'>Three</Link>
<Link to='/Four'>Four</Link>
</div>
)
class App extends Component {
componentWillMount() {
this.setState({routeKey:this.props.location.pathname})
this.setState({routes: [
(<Route exact path="/One" component={One}/>),
(<Route exact path="/Two" component={Two}/>),
(<Route exact path="/Three" component={Three}/>),
(<Route exact path="/Four" component={Four}/>)
]})
}
render() {
return (
<div className="App">
<div>
<MyNav/>
<ReactCSSTransitionGroup
transitionName="PageSlider"
transitionEnterTimeout={0}
transitionLeaveTimeout={150}>
<Switch key={this.props.location.pathname}>
<Route exact path="/One" component={One}/>
<Route exact path="/Two" component={Two}/>
<Route exact path="/Three" component={Three}/>
<Route exact path="/Four" component={Four}/>
</Switch>
</ReactCSSTransitionGroup>
</div>
</div>
);
}
componentWillReceiveProps(newProps) {
this.setState({routeKey:newProps.location.pathname})
}
}
export default App;
specify .PageSlider-enter, .PageSlider-enter.PageSlider-enter-active, .PageSlider-leave, .PageSlider-leave.PageSlider-leave-active accordingly

Resources