How to reset useState everytime I change my page? - reactjs

I'm working on a Hamburger Navbar
here is my page look like:
the issues is whenever I clicked to another route but the navbar still appear on right side. I want to make it whenever I go to another route it will disappear.
Here is my code:
const App = (props) => {
const [ menuOpen, setMenuOpen ] = useState(false);
<HamburgerNav>
<HamburgerNavContainer>
<LogoLinkStyled to="/">
<LogoNav src="https://thebeuter.com/wp-content/uploads/2020/04/logo-black.png" />
</LogoLinkStyled>
<HamburgerUtilities>
<HamburgerUlityItem>
<Icon className="fal fa-search fa-rotate-90" onClick={openModalHandler} />
</HamburgerUlityItem>
<HamburgerUlityItem>
<Link to="/cart" style={{ color: 'black', textDecoration: 'none' }}>
<Icon className="fal fa-shopping-bag" />
<CartNumb>({props.basketProps.basketNumbers})</CartNumb>
</Link>
</HamburgerUlityItem>
<HamburgerUlityItem>
<HamburgerLine onClick={() => setMenuOpen(!menuOpen)} />
</HamburgerUlityItem>
</HamburgerUtilities>
</HamburgerNavContainer>
</HamburgerNav>
How can I fix this problem? Really appreciate it.!!!
Github project: https://github.com/nathannewyen/the-beuter
update Router code:
Here is my Router for all routes in navbar
<Router>
<ContactForm path="/contact" />
<SizeChart path="/size-chart" />
<ShippingAndReturn path="/shipping-return" />
<PrivacyAndPolicy path="/privacy-policy" />
<AboutUs path="/about-us" />
<ShopAllProducts path="/" />
<NewArrival path="/shop/new-arrival" />
<Tops path="/product-category/top" />
<Bottoms path="/product-category/bottom" />
<Product path="/product/:title_url" />
<SearchInfo path="/search/:title" searchTerm={searchTerm} title="Profile" />
<Cart path="/cart" />
<Checkout path="/checkout" />
</Router>

You need to add onClick to the "route" component that is not closing it and do something like this:
onClick={() => { setMenuOpen(prevState => {return !prevState}) }}
If for example you want it to close when you click on "T-Shirts", then "T-Shirts" must also have that onClick.
If you already have onClicks on these components with another function, you can just add multiple functions inside the anonymous function like this:
onClick={() => {
YourOtherFunction();
setMenuOpen(prevState => {return !prevState});
}
If your components are not in the App.js you need to somehow pass the onClick down too them.
Since its a state you wont be able to pass down the setMenuOpen itself, you need a wrapper function. So first create the wrapper:
const setMenuOpenWrapper = () => {
setMenuOpen(prevState => return { !prevState });
}
Then pass it down to the childrens like:
and then inside your ContactForm on the link to the contact form add the onClick:
...onClick={() => { closeMenuFunction(); }}
Ok I just checked your code, you need to pass down the function to the Sidenav component.
So in your App.js first create the wrapper function as I explained above
After that again in App.js on line 316 where you have <SideNav menuOpen={menuOpen} /> change it to <SideNav menuOpen={menuOpen} closeMenuFunction={setMenuOpenWrapper}/>
Then in your Sidenav.jsx on all of your menu items add an onclick:
onClick={props.closeMenuFunction}
And then it should work.

Related

how to change url without adding another level of path in react router dom 5

i have an api "xyz.com/products/" and i have made an route xyz.com/products/1. This will give me an product with the id 1 . And it will render product page Component with that product details...But now on that particular product page i have an gallery of related product with their own individual "Link" to open in same product page . but when i click on any one of them ....the url changes like this "xyz.com/product/1/23" but i want only to change path like "xyz.com/products/1" --> "xyz.com/products/23"
here is my code snippets
// ///// route and link both are on App Component/////////////////
// this is the route that i have that matches xyz.com/product/1
<Route
path="/product/:id"
render={() => (
<Fragment>
<ProductContext.Provider value={{ productState, productStateDispatch }}>
<Product />
<div className={`overlay ${productState.packageSidebar}`}></div>
</ProductContext.Provider>
</Fragment>
)}
/>;
these are links will go on product page
<Row title="Our best seller">
{homeState.bestSellerProducts.map((product, index) => (
<Link
to={{
pathname: `/product/${product.id}`,
search: `type=${product.type}`,
}}
className="product-link"
key={index}
>
{" "}
<Card {...product} />
</Link>
))}
</Row>
//////////////////////////////
// this is in my product component where i have used one more component called imageGallery inside it. in which we have links////////////
{images.map((imgObj, index) => {
console.log(imgObj);
return (
<div className="item" key={index}>
<Link to={`/${imgObj.id}`} className="product-link">
<div className="img">
<img
height={100}
width={100}
src={imgObj.product_image}
alt="product-img"
/>
</div>
</Link>
</div>
);
})}
// i know i messing in routing i hope will get solution.... i just want that when i click on any link in this imageGallery component .it should be open inside same product page in which i m already present.. thats it
Including exact keyword in the Route component might solve your problem, try out!, demo example:
<Route exact to='/' component={home} />

No impact on URL with Material-UI BottomNavigation

I am trying to create a Bottom Navigation bar using material-ui (link:https://material-ui.com/components/bottom-navigation/).
Unfortunately, when I created the component, clicking on each tap did not affect my URL.
Initially, I was using the Link component from React, which allowed me to route between various components. However, as I integrate the Link component into the BottomNavigation component, the style changes and is not working properly anymore.
Here's my current code (without the Link component):
function NavigationAuth() {
const [value, setValue] = React.useState("/");
const handleChange = (event, newValue) => {
setValue(newValue);
};
return (
<BottomNavigation
value={value}
onChange={handleChange}
showLabels
>
<BottomNavigationAction label="Home" value="/" icon={<HomeIcon />} />
<BottomNavigationAction label="Progress" value="/home" icon={<TimelineIcon />} />
<BottomNavigationAction label="Vote" value="/overview" icon={<ThumbsUpDownIcon />} />
<BottomNavigationAction label="Account" value="/account" icon={<AccountCircleIcon />} />
</BottomNavigation>
);
}
Does anyone have an idea how I can actually change the URL (while using the BottomNavigation component) as a normal Link component would do?
Many thanks in advance!
You can import {useHistory} from react-router-dom and use it to change the URL:
function NavigationAuth() {
const [value, setValue] = React.useState("");
const history = useHistory();
const handleChange = (event, newValue) => {
history.push(`/${newValue}`);
setValue(newValue);
};
return (
<BottomNavigation
value={value}
onChange={handleChange}
showLabels
>
<BottomNavigationAction label="Home" value="" icon={<HomeIcon />} />
<BottomNavigationAction label="Progress" value="progress" icon={<TimelineIcon />} />
<BottomNavigationAction label="Vote" value="overview" icon={<ThumbsUpDownIcon />} />
<BottomNavigationAction label="Account" value="account" icon={<AccountCircleIcon />} />
</BottomNavigation>
);
}
You need both react-router and material-ui to accomplish what you're describing. Material-ui is a UI library and has no intention of providing functionality like routing, only the UI to control routing however you see fit.
Instead of using Link, and assuming this component is wrapped by BrowserRouter at a higher level, change the URL in your handleChange function like this:
const handleChange = (event, newValue) => {
props.history.push(newValue);
};
history is a prop injected by react-router that lets you programmatically update the URL by calling push.
The other way to do this would be the useHistory hook instead of passing it as a prop.

No translation for MenuItemLink's primaryText in react-admin

I'm using a custom user menu and the primarytext is not translated as expected.
No problems with the others components.
const MyUserMenu = props =>
<UserMenu {...props}>
<MenuItemLink
to="/configuration"
primaryText="labels.configuration"
leftIcon={<SettingsIcon />}
/>
</UserMenu>
You'll have to explicitly translate it as the MenuItemLink component is not currently responsible for translations (might be a good feature request btw).
import { translate, UserMenu, MenuItemLink, translate } from 'react-admin';
const MyUserMenu = translate(({ translate, ...props }) =>
<UserMenu {...props}>
<MenuItemLink
to="/configuration"
primaryText={translate("labels.configuration")}
leftIcon={<SettingsIcon />}
/>
</UserMenu>
it should be wrapped with curly brackets
"{labels.configuration}"

How to show a loading spinner until component loads in React

My question is not as simple as the title. I'm trying to show a loading component for 1 second and then replace that component with the actual data.
Here is my code:
const TopNavigationAuth = () => (
<Container>
<Menu.Item
name="landing"
content="Landing"
as={Link}
to={routes.LANDING}
/>
<Menu.Item name="home" content="Home" as={Link} to={routes.HOME} />
<Menu.Menu position="right">
<Menu.Item
name="account"
content="Account"
as={Link}
to={routes.ACCOUNT}
/>
<UserSection />
<Menu.Item
name="signout"
content={
<Button
content="Sign Out"
onClick={authFunctions.doSignOut}
primary
/>
}
/>
</Menu.Menu>
</Container>
);
So here I have the <UserSection /> component which essentially just holds the user's picture and name (for now). I would like to load that component after 1 or 2 seconds but until then I would like to show a spinner instead.
I'm using semantic ui react for my app and they have a handy spinner which looks like this:
const LoaderExampleInlineCentered = () => <Loader active inline='centered' />
Can I please have some guidance with this?
You can conditionally render one of the two components, Loader Or UserSection.
this.state.profileExist === true ? <UserSection /> : <Loader />
Then initialize profileExist as a False in componentDid mount, then use setTimeout to set it to true
componentDidMount() {
this.setState({profileExist: false})
setTimeout(() => {
this.setState({profileExist: true})
}, 1000);
}

reactjs Link not working,when render after ajax request

I want render a table from ajax request data. Each row with a action link to enter a edit page.when I click the link, the url on browser was changed,but it can't enter edit page.
In addition, when I click link button, the url on browser is not I except. (It's http://192.168.1.186:4444/table/basic-table2/articles rather than http://192.168.1.186:4444/#/table/basic-table2/articles).
I'm thinking the problem maybe cause by lifecycle of component mounting. Because when I put Link element out side the table(not wait ajax request return), it work well.
I'm new in React, Can anyone finger out where I am wrong?following is the code:
renderOperator = (value, index, record) => {
const edit = <Link exact="true" to="/table/basic-table2/articles">编辑</Link>;
const context = {};
return (
<div>
<Router context={context}>
<span>
{edit}
</span>
</Router>
<a
style={styles.removeBtn}
onClick={this.deleteItem.bind(this, record)}
>
删除
</a>
</div>
);
};
fllowing is the table:
<Table
dataSource={this.state.dataSource}
isLoading={this.state.isLoading}
rowSelection={{
...this.rowSelection,
selectedRowKeys: this.state.selectedRowKeys,
}}
>
<Table.Column title="编码" dataIndex="article_id" width={120} />
<Table.Column title="名称" dataIndex="article_title" width={250} />
<Table.Column title="报名数" dataIndex="enrolled_num" width={160} />
<Table.Column title="访问人数" dataIndex="visited_user_num" width={160} />
<Table.Column title="访问次数" dataIndex="visited_num" width={120} />
<Table.Column title="转载数" dataIndex="reprinted_num" width={120} />
<Table.Column
title="操作"
cell={this.renderOperator}
lock="right"
width={120}
/>
</Table>
I think the issue may be that you're including an instance of <Router /> inside if the <Table.Column />. You shouldn't need to create a separate instance for every <Link />
Try removing the <Router /> inside of renderOperator
It took me a while to understand your question.
Firstly, please check if there is any console errors in your browser. If yes, it may block your UI router to view the page.
Secondly, if you are using react-router, here is a link to the hash router usage: https://reacttraining.com/react-router/web/api/HashRouter. Basically, you need to wrap the routes with <HashRouter>.
Lastly, a few tips to improve your code, not related to your question:
You can use <React.Fragment> to replace your <div> wrapper
You can use items.map() to iterate through the list of Table.Column.

Resources