Reactjs sidebar doesn't collapse and dropdown doesn't open - css

I am trying to achieve two things:
(1) each time I click on the red arrow icon in the sidebar, I want the sidebar to collapse or open. From the below video, you'd see that the active and inactive states are already there. However, the sidebar doesn't collapse on inactive.
(2) each time I click on the Content menu, which is a drowndown menu, it doesn't open the submenu. Also, from the below video, you'd notice that the active and inactive states are already there. However, the dropdown still doesn't open on active.
Below is the video that clearly shows the error:
https://www.loom.com/share/6e0488101cee4c5b9bac7ded782b8807
Docs.js Page
import React from "react";
import { Helmet } from "react-helmet";
import SideMenu from "../docs/SideMenu";
const Docs = () => {
return (
<div className="">
<Helmet>
<title>Docs :: MyApp</title>
<meta name="description" content="MyApp" />
</Helmet>
<SideMenu />
</div >
)
};
export default Docs
SideMenu.js Component
import React, { useState } from "react";
import { Helmet } from "react-helmet";
import * as Icon from "react-bootstrap-icons";
import MenuItems from "./MenuItems";
const SideMenu = () => {
const [inActive, setInActive] = useState(false)
return (
<div className="">
<div className={`side-menu ${inActive ? "inActive" : ""}`}>
<Helmet>
<title>Docs :: MyApp</title>
<meta name="description" content="MyApp" />
</Helmet>
<div className="top-section">
<div className="logo">
<img src="/assets/media/logos/naked.png" alt="MyApp" />
</div>
<div onClick={() => setInActive(!inActive)} className="toggle-back">
{inActive ? (<Icon.ArrowLeftSquareFill />) : (<Icon.ArrowRightSquareFill />)}
</div>
</div>
<div className="search-bar">
<button className="search-bar-btn">
<Icon.Search />
</button>
<input type="text" placeholder="search" />
</div>
<div className="divider"></div>
<div className="main-menu">
<ul>
{menuItems.map((menuItem, index) => (
<MenuItems
key={index}
name={menuItem.name}
to={menuItem.to}
subMenu={menuItem.subMenu || []} />
))}
{/*<li>
<a className="menu-item">
<Icon.ArrowRightSquareFill className="menu-icon" />
<span>Dashboard</span>
</a>
</li>
<MenuItems
name={"Content"}
subMenu={[
{ name: 'Courses' },
{ name: 'Videos' },
]}
/>
<li>
<a className="menu-item">
<Icon.ArrowRightSquareFill className="menu-icon" />
<span>Support</span>
</a>
</li>*/}
</ul>
</div>
<div className="side-menu-footer">
<div className="avatar">
<img src="/assets/media/avatars/aa/brooks_lloyd.png" alt="MyApp" />
</div>
<div className="user-info">
<div className="font-size-h6">Title</div>
<div className="font-size-sm">Subtitle</div>
</div>
</div>
</div>
</div>
);
};
export default SideMenu
const menuItems = [
{ name: "Dashboard", to: "/" },
{ name: "Content", to: "/", subMenu: [{ name: "Courses" }, { name: "Videos" }], },
{ name: "Design", to: "/" },
];
MenuItems.js Component
import React, { useState } from "react";
import * as Icon from "react-bootstrap-icons";
const MenuItems = (props) => {
const { name, subMenu } = props;
const [expand, setExpand] = useState(false);
return (
<div className="">
<li>
<a onClick={() => setExpand(!expand)} className="menu-item">
<Icon.ArrowRightSquareFill className="menu-icon" />
<span>{name}</span>
</a>
{
subMenu && subMenu.length > 0 ? (
<ul className={`sub-menu ${expand ? "active" : ""}`}>
{subMenu.map((menu, index) =>
<li key={index}>
<a className="sub-menu">
<Icon.ArrowRightSquareFill className="menu-icon" />
{menu.name}
</a>
</li>
)}
</ul>) : null}
</li>
</div>
);
};
export default MenuItems
Docs.css File that contains the suspected errors, which are the side-menu and sub-menu lines:
.side-menu {
position: fixed;
background: #000;
width: 300px;
height: 100%;
box-sizing: border-box;
padding: 30px 20px;
transition: width .2s ease-in;
}
.side-menu.inactive {
width: 80px;
}
.side-menu .main-menu .sub-menu {
color: #333;
margin-left: 20px;
border-left: 1px solid #666;
box-sizing: border-box;
padding-left: 30px;
max-height: 0;
overflow: hidden;
transition: max-height .2s ease-in;
}
.side-menu .main-menu .sub-menu.active {
max-height: 200px;
}

Related

How to change the CSS of a targeted div

I am creating an interactive rating card with react. I have 5 divs which represent the number you are rating. When I click on one number I want to change the background of the targeted div to white.
import './App.css';
import React, { useState } from 'react';
function App() {
const [color, setColor] = useState('blue');
const changeColor = () => {
setColor('white');
};
return (
<div className="card">
<div className="container">
<p class="question">How did we do?</p>
<p>
Please let us know how we did with your support request. All feedback
is appreciated to help us improve our offering!
</p>
<div id="numbers">
<div
className="circle"
onClick={setColor}
style={{ backgroundColor: color }}
>
1
</div>
<div
className="circle"
onClick={changeColor}
style={{ backgroundColor: color }}
>
2
</div>
<div className="circle">3</div>
<div className="circle">4</div>
<div className="circle">5</div>
</div>
<button className="btn"> Submit </button>
</div>
</div>
);
}
export default App;
So far I tried to work with an useState hook. I read in some other sources to use the e.target.value or to give every div a special key value. I tried it with both but didn't manage to solve it. At the moment div 1 and div 2 change the color if I click on one of them.
const App = () => {
const [selectedStar, setSelectedStar] = React.useState();
return (
<div>
<div
className={`circle ${selectedStar === 1 && "active"}`}
onClick={() => setSelectedStar(1)}
>
1
</div>
<div
className={`circle ${selectedStar === 2 && "active"}`}
onClick={() => setSelectedStar(2)}
>
2
</div>
<div
className={`circle ${selectedStar === 3 && "active"}`}
onClick={() => setSelectedStar(3)}
>
3
</div>
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
.circle {
height: 20px;
width: 20px;
background: blue;
text-align: center;
color: white;
border-radius: 50%;
}
.circle.active {
background: white;
color: black;
}
<script src="https://unpkg.com/react#16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16.7.0-alpha.0/umd/react-dom.development.js"></script>
<div id="root"></div>

organize Css menu-bars

i had create a menu-bars hamburger inside the app.js file to show it when I click on the 3bars alls is good but I had a problem related to CSS so when I click on icons-bar the menubar display very well but the other menu navbar on the right of it disappear.to be honest with you I'm not hero in CSS.this is my code :
app.js file:
import {useState} from "react";
import {BrowserRouter, Routes, Route, Link} from "react-router-dom";
import {useSelector} from "react-redux";
import HomePage from "./Pages/HomePage";
import ProductPage from "./Pages/ProductPage";
import CartPage from "./Pages/CartPage"
function App() {
const cart = useSelector(state=> state.cart);
const productsList = useSelector(state=> state.productsList);
const { products } = productsList;
const categories = products?.length
? products.map(({category})=> category)
: [];
const [open, setOpen] = useState(false);
const allCategories = categories.filter((element, index, categories)=> element !== categories[index + 1]);
console.log(allCategories)
const { cartProducts } = cart;
const menuBar = () => {
return (
<div className={open ?"bars": "bars-close"} >
{allCategories.map((category, index)=> <div key={index} className="bar" >{category}</div>
)}
</div>
)
}
console.log(open)
return (
<BrowserRouter>
<div className="grid-container" >
<header className="row">
<div>
<Link className="brand" to="/">My shop</Link>
<span className ="menu-bar">
<i onClick={()=> setOpen(!open)} className="fa fa-bars"></i>
</span>
{menuBar()}
</div>
<div>
<Link to="/cart/:id">Cart
{cartProducts.length > 0 && (
<span className="badge" >{cartProducts.length}</span>
)}
</Link>
<Link to="/signin">Sign In</Link>
</div>
</header>
<main>
<Routes>
<Route path="/cart/:id" element={<CartPage />} ></Route>
<Route path="/product/:id" element={<ProductPage />} exact ></Route>
<Route path="/" element={<HomePage />} ></Route>
</Routes>
</main>
<footer className="row center" >All right reserved</footer>
</div>
</BrowserRouter>
);
}
export default App;
index.css file just the part of menu-bars:
.bars {
display: block;
width: 20rem;
background-color: #101010;
height: 80px;
transition-delay: 400ms;
z-index: 2;
position: relative;
left: 5rem;
}
.bars-close {
display: none;
transition-delay: 500ms;
}
.bars .bar {
font-size: 2rem;
color: #fff;
text-decoration: underline;
margin: 0.2rem 0;
text-align: center;
}
.menu-bar {
color: #ffffff;
}
.menu-bar i {
margin-left: 2rem;
font-size: 3rem;
cursor: pointer;
}

How do i bind a css stylesheet to only 1 react component?

I am using a React Template, where i inserted a shopping cart site using some react and Simple HTML (The code is below the question). Also i have a index.css file, which contains the css for the shopping cart. My goal is to implement the css only in the shopping cart site.
I tried to "import './index.css' inside my shopping cart.
The problem was as follows: After rendering the shopping cart, the css was applied to every other site as well.
How is it possible to use the css code only in the shopping cart?
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Link } from 'react-router-dom';
import { addToCart, removeFromCart } from '../../frontend/actions/cartActions';
import MessageBox from '../../frontend/MessageBox';
import { useLocation } from 'library/hooks/useLocation';
export default function CartScreen(props) {
// Namen
var a = window.location.href;
var b = a.substring(a.indexOf("?")+1)
const productId = b;
console.log(productId)
// redux store
const cart = useSelector((state) => state.cart);
const { cartItems, error } = cart;
const dispatch = useDispatch();
useEffect(() => {
if (productId) {
dispatch(addToCart(productId));
}
}, [dispatch, productId]);
const removeFromCartHandler = (id) => {
// delete action
dispatch(removeFromCart(id));
};
const checkoutHandler = () => {
props.history.push('/signin?redirect=shipping');
};
return (
<div className="row top">
<div className="col-2">
<h1>Shopping Cart</h1>
{error && <MessageBox variant="danger">{error}</MessageBox>}
{/* display cart or message if empty */}
{cartItems.length === 0 ? (
<MessageBox>
Cart is empty. <Link to="/">Go Shopping</Link>
</MessageBox>
) : (
<ul>
{cartItems.map((item) => (
<li key={item.product}>
<div className="row">
<div>
<img
src={item.image}
alt={item.name}
className="small"
></img>
</div>
<div className="min-30">
<Link to={`/product/${item.product}`}>{item.name}</Link>
</div>
<div>
<select
value={item.qty}
onChange={(e) =>
dispatch(
addToCart(item.product, Number(e.target.value))
)
}
>
{[...Array(item.countInStock).keys()].map((x) => (
<option key={x + 1} value={x + 1}>
{x + 1}
</option>
))}
</select>
</div>
<div>${item.price}</div>
<div>
<button
type="button"
onClick={() => removeFromCartHandler(item.product)}
>
Delete
</button>
</div>
</div>
</li>
))}
</ul>
)}
</div>
<div className="col-1">
<div className="card card-body">
<ul>
<li>
<h2>
Subtotal ({cartItems.reduce((a, c) => a + c.qty, 0)} items) : $
{cartItems.reduce((a, c) => a + c.price * c.qty, 0)}
</h2>
</li>
<li>
<button
type="button"
onClick={checkoutHandler}
className="primary block"
disabled={cartItems.length === 0}
>
Proceed to Checkout
</button>
</li>
</ul>
</div>
</div>
</div>
);
}
import './index.css'
give the div in the html a specific name: <div className="cartScreen">
in css, specify the element where the style should be used:
body .cartScreen{
margin: 0;
height: 100vh;
font-size: 1.6rem;
font-family: Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

Doing custom hover animation on nav items(bootstrap nav) but the effect isn't visible in my react application

I'm trying to add custom hover effect on my nav Items using ext CSS but when I import it in my Navbar the bootstrap isn't overwritten and the effect isn't visible and also when the navBar collapses the three line isn't visible but when I click on the top right corner it's there and works fine
**
Here is my NAVBAR.JS file for react
**
import React, { Component } from 'react';
import { Navbar, Nav, Button } from 'react-bootstrap';
import styles from './Navbar.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Link } from 'react-router-dom';
const links = [
{
href: '/novels/601e73a75e4fd540506c9938',
text: 'Novel',
},
{ href: '#', text: 'Buy EA Coins' },
{ href: '#', text: 'Get Started' },
{ href: '#', text: 'Library' },
{ href: '/', text: 'home' },
];
const createNavItem = ({ href, text, className }) => (
<Nav.Item>
<Nav.Link className={className}>
<Link to={href}> {text}</Link>
</Nav.Link>
</Nav.Item>
);
class NavbarMain extends Component {
constructor(props) {
super(props);
this.state = {
key: 'home',
};
this.handleSelect = this.handleSelect.bind(this);
}
handleSelect(key) {
this.setState({
key: key,
});
alert(`selected ${key}`);
}
render() {
return (
<Navbar
bg="light"
variant="danger"
expand="lg"
fixed-top
className={styles.test}
>
<Navbar bg="light">
<Navbar.Brand>
<Link to="/" exact>
<img
src="EA-Logo-edit.png"
width="90"
height="70"
margin="none"
className="d-inline-block align-top"
alt="React Bootstrap logo"
style={{ margin: 'none' }}
/>
</Link>
</Navbar.Brand>
</Navbar>
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="mr-auto" activeKey="/" className={styles.avbar}>
{links.map(createNavItem)}
</Nav>
<Nav className="ml-auto" navbar>
<Nav.Item>
<Nav.Link href="#discord">
<Button variant="outline-dark">
<img height={25} width={40} src="discord.svg" alt="" />
Discord
</Button>
</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link href="/auth/login">
<Button variant="outline-dark">
<img height={25} width={40} src="google.svg" alt="" />
Login
</Button>
</Nav.Link>
</Nav.Item>
</Nav>
</Navbar.Collapse>
</Navbar>
);
}
}
export default NavbarMain;
Here is my CSS file
:local(.navbar.hover::before){
position: relative;
}
:local(.navbar:before){
content: "";
position: absolute;
width: 100%;
height: 2px;
bottom: 0;
left: 0;
background-color: #000;
visibility: hidden;
transform: scaleX(0);
transition: all 0.3s ease-in-out 0s;
}
:local(.navbar:hover){
color: #000;
}
:local(.navbar){
position: relative;
color: #000;
text-decoration: none;
}
You can fix overwrite problem with !important like this
:local(.navbar:hover){
color: #000 !important;
}

How to handle z-index on React components on a table

I'm having some issues while displaying a modal on a table. For each expense data I render a expenseItem component inside of a tbody. When clicking on this components, it opens a lateral modal and a backdrop on the remaining screen.
Backdrop has a action that whenever is clicked, it closes modal. But, when I click inside of modal, it calls close modal action of backdrop on top of it.
I've tried to set z-index of backdrop to 100 and moda to 200. It didn't work.
return (
<tr className="expense-box" onClick={() => handleOpenModal()}>
<td className="expense-info">{description}</td>
<td>-</td>
<td>-</td>
<td className="expense-info">{date}</td>
<td className="expense-info">{debit || credit}</td>
<td>
<BackDrop isShowing={isModalOpen} closeModal={handleOpenModal} />
<EditExpenseModal isShowing={isModalOpen} closeModal={handleOpenModal} expense={props.expense} />
</td>
</tr>
Backdrop component:
function BackDrop({ isShowing, closeModal }) {
return (
<div onClick={closeModal}>
{isShowing ? <div className="backDrop" /> : null}
<style jsx>
{`
.backDrop {
position: fixed;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.3);
z-index: 100;
top: 0;
left: 0;
}
`}
</style>
</div>
);
}
export default BackDrop;
Modal component:
import { useState, Fragment } from 'react';
import { editExpenses } from '../redux/actions/expenseActions';
import DropdownMenu from '../components/dropdownMenu';
import { connect } from 'react-redux';
import { createPortal } from 'react-dom';
const EditExpenseModal = ({ expense, isShowing, closeModal, editExpenses, savedCategories }) => {
const { id, description, date, credit, debit } = expense;
const [ expenseItem, setExpenseItem ] = useState({
date,
description,
category: '',
subcategory: '',
credit,
debit
});
function handleInputChange(e, targetName) {
const { name, value } = e.target;
(value && !targetName) || (!value && !targetName)
? setExpenseItem({ ...expenseItem, [name]: value })
: setExpenseItem({ ...expenseItem, [targetName]: e.currentTarget.innerText });
}
function onEditExpense(id, expense) {
editExpenses(id, expense);
closeModal();
}
return isShowing
? createPortal(
<Fragment>
<div>
<div className="form">
<form>
<ul>
<li className="form-inputs">
<label>Date</label>
<input
className="field-input"
type="text"
name="date"
defaultValue={date}
onChange={handleInputChange}
/>
</li>
<li className="form-inputs">
<label>Description</label>
<input
className="field-input"
type="text"
name="description"
defaultValue={description}
onChange={handleInputChange}
/>
</li>
<li className="form-inputs">
<label>Category</label>
<DropdownMenu
savedCategories={savedCategories}
handleInputChange={handleInputChange}
type={'category'}
category={expenseItem.category}
/>
</li>
<li className="form-inputs">
<label>Subcategory</label>
<DropdownMenu
savedCategories={savedCategories}
handleInputChange={handleInputChange}
type={'subcategory'}
parentCategory={expenseItem.category}
category={expenseItem.subcategory}
/>
</li>
<li className="form-inputs">
<label>Credit</label>
<input
className="field-input"
type="text"
name="credit"
defaultValue={credit}
onChange={handleInputChange}
/>
</li>
<li className="form-inputs">
<label>Debit</label>
<input
className="field-input"
type="text"
name="debit"
defaultValue={debit}
onChange={handleInputChange}
/>
</li>
</ul>
</form>
<button onClick={() => onEditExpense(id, expenseItem)}>save</button>
<button onClick={() => closeModal()}>close</button>
</div>
<style jsx>{`
.form {
position: fixed;
background: white;
box-shadow: 0px 20px 5px rgba(0, 0, 0, 0.7);
display: flex;
flex-direction: column;
height: 100%;
top: 0;
right: 0;
width: 40%;
z-index: 200;
overflow: scroll;
}
.form-inputs {
display: flex;
flex-direction: column;
list-style-type: none;
padding: 1rem 2rem;
}
.form-inputs label {
margin-left: 8px;
}
.field-input {
margin: 5px;
width: 330px;
height: 40px;
font-size: 15px;
outline: none;
}
`}</style>
</div>
</Fragment>,
document.body
)
: null;
};
const mapDispatchToProps = (dispatch) => ({
editExpenses: (id, expense) => dispatch(editExpenses(id, expense))
});
const mapStateToProps = (state) => state;
export default connect(mapStateToProps, mapDispatchToProps)(EditExpenseModal);
This problem started to happen when I've turned all structure to a table. Before I was using only <div> and it was working.

Resources