scrolling has some problems - javascript

i using coreUi template for my reactJS project & in that when some component scrolling i can't have smooth scrolling which means i can scroll about bit first time and then again i have move courser bit and do the scrolling to go down of page..this is only happens with small screens (ex 1280px * 1024)
this is a gif file which showing the problem :
and here is the place where my all components are handling :
import React, { Component, Suspense, Fragment } from "react";
import { Route, BrowserRouter as Router } from "react-router-dom";
import * as router from "react-router-dom";
import { Container } from "reactstrap";
import { logout } from "../../actions/authActions";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import {
AppHeader,
AppSidebar,
AppSidebarFooter,
AppSidebarForm,
AppSidebarHeader,
AppSidebarMinimizer,
AppBreadcrumb2 as AppBreadcrumb,
AppSidebarNav2 as AppSidebarNav
} from "#coreui/react";
// sidebar nav config
import NavigationBar from "../../menu";
// routes config
import routes from "../../routes";
import { connect } from "react-redux";
import { loading } from "./LoadingComponent";
import ButtonPermission from "../../permission";
const DefaultHeader = React.lazy(() => import("./DefaultHeader"));
const Dashboard = React.lazy(() => import("./../../views/Dashboard/Dashboard"));
class DefaultLayout extends Component {
constructor() {
super();
this.currentNavigation = new NavigationBar().createMenu();
this.routes = new ButtonPermission().setPermission(routes);
}
signOut(e) {
e.preventDefault();
this.props.history.push("/login");
this.props.LOGOUT();
}
render() {
const divProps = Object.assign({}, this.props);
delete divProps.LOGOUT;
return (
<div className="app scroller">
<AppHeader fixed>
<Suspense fallback={loading()}>
<DefaultHeader onLogout={e => this.signOut(e)} />
</Suspense>
</AppHeader>
<div className="app-body">
<AppSidebar fixed display="lg">
<AppSidebarHeader />
<AppSidebarForm />
<Suspense>
<AppSidebarNav
navConfig={this.currentNavigation}
{...divProps}
router={router}
/>
</Suspense>
<AppSidebarFooter />
<AppSidebarMinimizer />
</AppSidebar>
<main className="main">
<AppBreadcrumb appRoutes={this.routes} router={router} />
<Container fluid>
<Suspense fallback={loading()}>
{this.routes.map((route, idx) => {
return route.component ? (
<Route
key={idx}
path={route.path}
exact={route.exact}
name={route.name}
render={props => (
<route.component {...props} {...route.props} />
)}
/>
) : (
<Fragment>
<Router
path="*"
name="home"
render={props => <Dashboard {...props} />}
/>
</Fragment>
////
////
);
})}
</Suspense>
<ToastContainer
autoClose={3000}
hideProgressBar
closeOnClick
pauseOnHover={false}
position="bottom-center"
/>
</Container>
</main>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
error: state.error
});
const mapDispachToProps = dispach => {
return {
LOGOUT: () => dispach(logout())
};
};
export default connect(mapStateToProps, mapDispachToProps)(DefaultLayout);
can i get more smooth scrolling in my reactJS project please! Thank you!

Related

In how many ways we can pass props to all child components in react

I have an app code
import React from "react";
import { Route, Switch } from "react-router-dom";
import Minidrawer from './components/Drawer/Minidrawer'
import { makeStyles } from '#mui/styles';
import Box from '#mui/material/Box';
import Main from "./components/Main/Main";
import {useSelector} from 'react-redux'
const useStyles = makeStyles({
container: {
display: "flex"
}
});
export default function App() {
const classes = useStyles();
const user = useSelector((state) => state.auth);
return (
<Box sx={{ display: 'flex' }}>
<Minidrawer currUser={user}/>
<Switch>
<Route exact from="/" render={props => <Main childText="home" currUser={user} {...props} />} />
<Route exact path="/auth" render={props => <Main childText="auth" currUser={user} {...props} />} />
<Route exact path="/register-client" render={props => <Main childText="registerClient" currUser={user} {...props} />} />
</Switch>
</Box>
);
}
I have to pass currUser to all child components imported in App but I do not want to duplicate the code, what are different ways to achieve this so that all of the components have access to currUser?
if I understand what you want to do, you want to pass props to all children of a component, if the components are simple components you can do as follows:
import React from "react";
import Main from "./Main";
import PassPropsToNormalComponents from "./PassPropsToNormalComponents";
export default function App() {
const user = {
username: "lakhdar"
};
return (
<div style={{ display: "flex" }}>
<PassPropsToNormalComponents currUser={user}>
<Main childText="home" />
<Main childText="auth" />
<Main childText="registerClient" />
</PassPropsToNormalComponents>
</div>
);
and this is the PassPropsToNormalComponents file
import React from "react";
export default function PassPropsToNormalComponents({ children, ...props }) {
const childrenWithProps = React.Children.map(children, (child) => {
if (React.isValidElement(child)) {
return React.cloneElement(child, { ...child.props, ...props });
}
return child;
});
return <>{childrenWithProps}</>;
}
but in your case passing the props to the routes wont' make the routes pass the props to their rendered components so we need an extra step here:
first the file where we provide the props to the parent:
import React from "react";
import { Route, Switch } from "react-router-dom";
import Main from "./Main";
import PassPropsToRouteComponents from "./PassPropsToRouteComponents";
export default function App() {
const user = {
username: "lakhdar"
};
return (
<div style={{ display: "flex" }}>
<Switch>
<PassPropsToRouteComponents currUser={user}>
<Route
exact
from="/"
render={(props) => {
return <Main childText="home" {...props} />;
}}
/>
<Route
exact
path="/auth"
render={(props) => <Main childText="auth" {...props} />}
/>
<Route
exact
path="/register-client"
render={(props) => <Main childText="registerClient" {...props} />}
/>
</PassPropsToRouteComponents>
</Switch>
</div>
);
}
and finally, the extra step is to get the rendered element and pass it its own props + the props from the parent, and the file looks like this:
import React from "react";
export default function PassPropsToRouteComponents({ children, ...props }) {
const childrenWithProps = React.Children.map(children, (child) => {
if (React.isValidElement(child)) {
const routerChild = child.props.render();
return React.cloneElement(child, {
...child.props,
render: () => {
return React.cloneElement(routerChild, {
...routerChild.props,
...props
});
}
});
}
return child;
});
return <>{childrenWithProps}</>;
}
link to working codesandbox: https://codesandbox.io/s/gracious-meadow-dj53s
I hope this is what you've been looking for.
You could use redux or the context API.
Redux: https://react-redux.js.org/
Context API: https://reactjs.org/docs/context.html

Getting error while redirect to the home page in react

I was trying to restrict logged in user to access login page using following code
import React, { useEffect, useState } from "react"; import { Route }
from "react-router-dom"; import { Redirect } from "react-router-dom";
const UserLayoutRoute = ({ component: Component, ...rest }) => {
const [loggedIn, setLoggedIn] = useState(null); useEffect(() => {
if (localStorage.getItem("cachedValue") !== null) {
setLoggedIn(true);
} }, []); return loggedIn ? (
<Route
{...rest}
render={matchProps => (
<div className="App">
<section className="user-page">
<div className="">
<div className="">
<Component {...matchProps} />
</div>
</div>
</section>
</div>
)}
/> ) : (
<Redirect to="/" /> ); };
export default UserLayoutRoute;
With this code page keep on loading and its not rendering anything.
I also posted this issue in GitHub https://github.com/facebook/react/issues/17514
I think that maybe you can try other approach like this
import React from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';
const PrivateRouteComponent = ({ component: Component, isAuth, ...rest }) => (
<Route
{...rest}
render={props => (
isAuth
? <Component {...props} />
: <Redirect to="/login" />
)}
/>
);
PrivateRouteComponent.propTypes = {
component: PropTypes.any.isRequired,
isAuth: PropTypes.bool.isRequired,
};
export default PrivateRouteComponent;
And in the case the routes
<Switch>
<PrivateRouteComponent exact path="/" component={**ComponentName**} isAuth={isAuth} />
</Switch>
For the case that the isAuth props maybe you can change that for your condition

React refresh component on login

I have 2 components, NavBar which contains a login modal and the 'body' of page.
I want to detect when a user logs in and re-render the page based on that. How do I update the login prop in the second component when I log in using the modal of the first one?
A simplified version of the code to keep it short:
// NavBar.js
export default class NavBar extends Component {
constructor(props) {
super(props)
this.initialState = {
username: "",
password: "",
loginModal: false
}
this.handleLogin = this.handleLogin.bind(this)
}
handleLogin(e) {
e.preventDefault()
loginAPI.then(result)
}
render() {
return( <nav> nav bar with links and login button </nav>)
}
// Some random page
export default class Checkout extends Component {
constructor(props) {
super(props);
this.state = {
order_type: 'none',
loggedIn: false
}
this.Auth = new AuthService()
}
componentDidMount() {
if (this.Auth.loggedIn()) {
const { username, email } = this.Auth.getProfile()
this.setState({ loggedIn: true, email: email })
}
try {
const { order_type } = this.props.location.state[0]
if (order_type) {
this.setState({ order_type: order_type })
}
} catch (error) {
console.log('No package selected')
}
}
componentDidUpdate(prevProps, prevState) {
console.log("this.props, prevState)
if (this.props.loggedIn !== prevProps.loggedIn) {
console.log('foo bar')
}
}
render() {
return (
<section id='checkout'>
User is {this.state.loggedIn ? 'Looged in' : 'logged out'}
</section>
)
}
}
// App.js
function App() {
return (
<div>
<NavBar />
<Routes /> // This contains routes.js
<Footer />
</div>
);
}
// routes.js
const Routes = () => (
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/register" component={Register} />
<Route exact path="/registersuccess" component={RegisterSuccess} />
<Route exact path="/faq" component={FAQ} />
<Route exact path="/checkout" component={Checkout} />
<Route exact path="/contact" component={Contact} />
{/* <PrivateRoute exact path="/dashboard" component={Dashboard} /> */}
<Route path="/(notfound|[\s\S]*)/" component={NotFound} />
</Switch>
)
I would recommend using the react context API to store information about the logged in user.
See: https://reactjs.org/docs/context.html
Example
auth-context.js
import React from 'react'
const AuthContext = React.createContext(null);
export default AuthContext
index.js
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import AuthContext from './auth-context.js'
const AppWrapper = () => {
const [loggedIn, setLoggedIn] = useState(false)
return (
<AuthContext.Provider value={{ loggedIn, setLoggedIn }}>
<App />
</AuthContext.Provider>
)
}
ReactDOM.render(
<AppWrapper/>,
document.querySelector('#app')
)
Then inside any component you can import the AuthContext and use the Consumer component to check if the user is logged in order set the logged in state.
NavBar.js
import React from 'react'
import AuthContext from './auth-context.js'
const NavBar = () => (
<AuthContext.Consumer>
{({ loggedIn, setLoggedIn }) => (
<>
<h1>{loggedIn ? 'Welcome' : 'Log in'}</h1>
{!loggedIn && (
<button onClick={() => setLoggedIn(true)}>Login</button>
)}
</>
)}
</AuthContext.Consumer>
)
export default NavBar
HOC version
with-auth-props.js
import React from 'react'
import AuthContext from './auth-context'
const withAuthProps = (Component) => {
return (props) => (
<AuthContext.Consumer>
{({ loggedIn, setLoggedIn }) => (
<Component
loggedIn={loggedIn}
setLoggedIn={setLoggedIn}
{...props}
/>
)}
</AuthContext.Consumer>
)
}
export default withAuthProps
TestComponent.js
import React from 'react'
import withAuthProps from './with-auth-props'
const TestComponent = ({ loggedIn, setLoggedIn }) => (
<div>
<h1>{loggedIn ? 'Welcome' : 'Log in'}</h1>
{!loggedIn && (
<button onClick={() => setLoggedIn(true)}>Login</button>
)}
</div>
)
export default withAuthProps(TestComponent)
Alternatively if you have redux setup with react-redux then it will use the context API behind the scenes. So you can use the connect HOC to wrap map the logged in state to any component props.

How come react-router-dom does not change URL on click?

I am having trouble changing the URL and getting the component to load when using react-router-dom. If I manually enter the URL the component will load, however, the URL (and component) does not change when I click on the link. In this case, I am trying to load the '/industry/aerospace' page. Thanks!
Here's my code:
App.js:
import React from 'react'
import { compose } from 'redux'
import { Route, Switch, withRouter } from 'react-router-dom'
import { MuiThemeProvider } from '#material-ui/core/styles'
import LandingPage from '../../home'
import AnalyzerProductPage from '../../home/analyzer'
import MonitorProductPage from '../../home/monitor'
import Signout from '../../home/signout'
import Industry from '../../home/industry'
class App extends React.PureComponent {
render() {
return (
<div>
<MuiThemeProvider theme={muiTheme} >
<Switch>
<Route exact path="/" component={LandingPage} />
<Route exact path="/version" component={Version} />
<Route exact path="/signout_success" component={LandingPage} />
<Route exact path="/signout" component={Signout} />
<Route exact path="/liquidtool-analyzer" component={AnalyzerProductPage} />
<Route exact path="/liquidtool-monitor" component={MonitorProductPage} />
<Route exact path="/industry/:industry" component={Industry} />
</Switch>
</MuiThemeProvider>
<NotificationHandler />
<RestCallProgressBar />
</div>
)
}
}
export default compose(
withRouter,
)(App)
HomeHeader.js (with link to page):
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom'
// material-ui
import { withStyles } from '#material-ui/core/styles'
class HomeHeader extends Component {
state = {
value: false,
anchorEl: null
};
handleIndustriesClick = (event) => {
this.setState({ anchorEl: event.currentTarget })
};
handleIndustriesClose = (pageID) => {
this.setState({ anchorEl: null })
}
handleDashboardClick = () => {
this.props.history.push('/dashboard')
};
handleChange = (event, value) => {
this.setState({ value })
};
render() {
const { classes } = this.props
const { value } = this.state
const { anchorEl } = this.state
return (
<AppBar className={classes.appBar} elevation={this.props.elevation}>
<Hidden smDown>
<Grid container justify="space-between" alignItems="center">
<Tabs value={value} onChange={this.handleChange}>
<Tab label="monitor" />
<Tab label="sensor" />
<Tab
label="industries"
aria-owns={anchorEl ? 'industries-menu' : null}
aria-haspopup={true}
onClick={this.handleIndustriesClick}
/>
<Menu
id="industries-menu"
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={this.handleIndustriesClose}
>
<MenuItem onClick={this.handleIndustriesClose}><Link to={'/industry/aerospace'}></Link>Aerospace</MenuItem>
</Menu>
</Tabs>
</Grid>
</Hidden>
</AppBar>
)
}
}
export default withStyles(styles)(HomeHeader)
Industry.js (Component to load):
import React, { Component } from 'react';
import Typography from '#material-ui/core/Typography';
import HomeHeader from '../components/HomeHeader'
class Industry extends Component {
render() {
return(
<div>
<HomeHeader />
<Typography>Hey</Typography>
</div>
)
}
}
export default Industry
try to wrap MenuItem from Link component:
<Link to='/industry/aerospace'>
<MenuItem>
Aerospace
</MenuItem>
</Link>
since you are using material-ui you can also use component prop in MenuItem (which will set the component as root)
<MenuItem component={Link} to='/industry/aerospace'>
Aerospace
</MenuItem>
hope this will help you

Why is react-transition-group not calling componentWillEnter nor componentWillLeave on route change?

I am following this hackernoon guide https://hackernoon.com/animated-page-transitions-with-react-router-4-reacttransitiongroup-and-animated-1ca17bd97a1a in order to apply enter and leave animations to my react components when a route changes. I have obviously adapted the code to fit my site, and have decided not to use Animated but rather just pure CSS. Right now I'm just testing the code with console.log statements, and I noticed that componentWillEnter and componentWillLeave are not being called on route changes. Also, componentWillAppear only gets called once.
Here is the relevant code for each component, including App.js and index.js:
Animated Wrapper:
import React, {Component} from "react";
import styles from '../styles/AnimatedWrapper.css';
const AnimatedWrapper = WrappedComponent =>
class AnimatedWrapper extends Component {
componentWillAppear(cb) {
console.log('componentWillAppear');
cb();
}
componentWillEnter(cb) {
console.log('componentWillEnter');
cb();
}
componentWillLeave(cb) {
console.log('componentWillLeave');
cb();
}
render() {
return (
<div id="animated-wrapper" className={styles.animatedPageWrapper}>
<WrappedComponent {...this.props}/>
</div>
);}
};
export default AnimatedWrapper;
App.js:
import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import TransitionGroup from "react-transition-group/TransitionGroup";
import Navbar from "./components/Navbar";
import Footer from "./components/Footer";
import Slider from "./components/Slider";
import ComingSoon from "./components/ComingSoon";
const firstChild = props => {
const childrenArray = React.Children.toArray(props.children);
return childrenArray[0] || null;
}
class App extends Component {
render() {
return (
<div className="App">
<Navbar />
<Switch>
<Route
path="/coming-soon"
children={({ match, ...rest }) => (
<TransitionGroup component={firstChild}>
{match && <ComingSoon {...rest} />}
</TransitionGroup>
)}/>
<Route
path="/"
children={({ match, ...rest }) => (
<TransitionGroup component={firstChild}>
{match && <Slider {...rest} />}
</TransitionGroup>
)}/>
</Switch>
<Footer />
</div>
);
}
}
export default App;
index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<BrowserRouter>
<App />
</BrowserRouter>,
document.getElementById('root')
);
Slider.js:
import React, { Component } from 'react';
import _ from 'lodash';
// components
import AnimatedWrapper from './AnimatedWrapper';
import Separator from './Separator';
// styles
import styles from '../styles/Slider.css';
// images
import Apartment from "../../public/images/apartment.jpg";
import Floor from "../../public/images/floor.jpg";
import Furniture from "../../public/images/furniture.jpg";
import Kitchen1 from "../../public/images/kitchen.jpg";
import Kitchen2 from "../../public/images/kitchen-2.jpg";
class SliderComponent extends Component {
constructor(props) {
super(props);
this.state = {
currentSlide: 0,
slides: [Apartment, Floor, Furniture, Kitchen1, Kitchen2]
};
}
componentDidMount() {
this.zoomAnimation();
this.slideContentAnimation();
this.sliderInterval = setInterval(() => {
if (this.state.currentSlide === 4) {
if (this.refs.slider) {
this.setState({ currentSlide: 0 });
}
} else {
if (this.refs.slider) {
this.setState({ currentSlide: this.state.currentSlide + 1 });
}
}
}, 6000);
}
componentWillUpdate() {
const currentContent = document.getElementById(`content-${this.state.currentSlide}`);
setTimeout(() => {
currentContent.classList.remove(`${styles.currentContent}`);
}, 1500);
}
componentDidUpdate() {
this.zoomAnimation();
this.slideContentAnimation();
}
setSlide(number) {
this.setState({ currentSlide: number });
}
zoomAnimation() {
setTimeout(() => {
const currentSlide = document.getElementById(`slide-${this.state.currentSlide}`);
currentSlide.classList.add(`${styles.slideZoom}`);
}, 500);
}
slideContentAnimation() {
setTimeout(() => {
const currentContent = document.getElementById(`content-${this.state.currentSlide}`);
if (currentContent) {
currentContent.classList.add(`${styles.currentContent}`);
}
}, 1500);
}
renderSlides() {
return this.state.slides.map((slide, index) => {
const isCurrent = index === this.state.currentSlide;
const slideStyle = {
backgroundImage: `url(${this.state.slides[index]})`
}
return (
<div
id={`slide-${index}`}
key={`slide-${index}`}
className={`
${styles.slide}
${isCurrent ? styles.currentSlide : null}
`}
style={slideStyle}
alt="slide">
<div
id={`content-${index}`}
key={`content-${index}`}
className={`
${styles.content}
`}>
<h1>{`WE SPECIALIZE IN KITCHENS ${index}`}</h1>
<Separator
containerWidth={720}
circleWidth={5}
circleHeight={5}
backgroundColor="#fff"
lineWidth={350}
lineColor="#fff"
/>
<div
className={`${styles['hvr-sweep-to-top']} ${styles.btn}`}>
More Information
</div>
</div>
</div>
);
});
}
renderNavBar() {
return (
<div className={styles.sliderNav}>
{_.range(5).map((index) => {
return (
<div
key={index}
onClick={() => this.setSlide(index)}
className={this.state.currentSlide === index ? styles.current : null}>
</div>
)
})}
</div>
)
}
render() {
return (
<div className={styles.container} ref="slider">
<div className={styles.slidesContainer}>
{this.renderSlides()}
</div>
{this.renderNavBar()}
</div>
);
}
}
const Slider = AnimatedWrapper(SliderComponent);
export default Slider;
ComingSoon.js:
import React from 'react';
import AnimatedWrapper from './AnimatedWrapper';
import styles from '../styles/ComingSoon.css';
const ComingSoonComponent = function() {
return (
<div>
<div className={styles.mainContent}>
<div>
<h1 className={styles.mainTitle}>{`Coming Soon`}</h1>
</div>
</div>
</div>
);
};
const ComingSoon = AnimatedWrapper(ComingSoonComponent);
export default ComingSoon;
Try to Use react-transition-group, it will be help.
You can use it like this Example. As follow main code:
import { BrowserRouter, Route, Switch, Link } from 'react-router-dom'
import { CSSTransition, TransitionGroup } from 'react-transition-group'
const PageFade = (props) => (
<CSSTransition
{...props}
classNames="fadeTranslate"
timeout={1000}
mountOnEnter={true}
unmountOnExit={true}
/>
)
const Layout = ({ children }) => (
<section>
<nav>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Non existing</Link></li>
</ul>
</nav>
<hr />
{children}
</section>
)
const App = (props) => {
const locationKey = props.location.pathname
return (
<Layout>
<TransitionGroup>
<PageFade key={locationKey}>
<section className="fix-container">
<Switch location={props.location}>
<Route exact path="/" component={Home} />
<Route exact path="/about" component={About} />
<Route component={NotFound} />
</Switch>
</section>
</PageFade>
</TransitionGroup>
</Layout>
)
}
const BasicExample = () => (
<BrowserRouter>
<Route path="/" component={App} />
</BrowserRouter>
);
render(<BasicExample />, document.getElementById('root'));

Categories

Resources