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;
}
Related
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>
I have a button navigation and when you click on a button, the active class is added. My goal is for the active class to be added to the button clicked, but remove that class of active on all other buttons if present. The 'About' button will have a class of active on page load.
Not sure how to translate this to React, in JavaScript on click I would remove the class from all the elements in a loop and add a class to the target clicked if it did not already have the active class.
Code Sandbox - https://codesandbox.io/s/toggle-active-on-class-clicked-remove-from-the-rest-r467l1?file=/src/App.js
export default function Header() {
const [active, setActive] = useState(true);
const toggleColor = function (e) {
// on load, 'About' button has active class
// when clicking another menu item add active class, remove active from the rest of buttons
console.log(e.target);
};
return (
<header className="header-img-container">
<nav>
<ul>
<li>
<button onClick={toggleColor} className={active ? "active" : ""}>
About
</button>
</li>
<li>
<button onClick={toggleColor}>Skills</button>
</li>
<li>
<button onClick={toggleColor}>Projects</button>
</li>
<li>
<button onClick={toggleColor}>Words</button>
</li>
</ul>
</nav>
</header>
);
}
There are so many ways to solve that problem. You can try this if it's meet your requirements.
import "./styles.css";
import { useState } from "react";
const list = ["About", "Skills", "Projects", "Words"];
export default function Header() {
const [activeLink, setActiveLink] = useState("About");
return (
<header className="header-img-container">
<nav>
<ul>
{list.map((item) => (
<li key={item}>
<button
onClick={() => setActiveLink(item)}
className={activeLink === item ? "active" : ""}
>
{item}
</button>
</li>
))}
</ul>
</nav>
</header>
);
}
Create a state like this
const [active, setActive] = useState({About: true, Skills: false, Projects: false, Words: false})
А change local parameter to add a class to element. For example
<li>
<button onClick={() => {
setActive({...active, About: false, Skills: true, Projects: false,
Words: false })
}}>Skills</button>
</li>
There are many possible approaches, here is a basic example that uses an object type active state to store the value for each list item.
const [active, setActive] = useState({ About: true })
The list data is stored in an array so it can be mapped in the JSX part of the component.
const itemList = ["About", "Skills", "Projects", "Words"]
While index is not an ideal key it is used here just for example purpose.
{
itemList.map((item, index) => (
<li key={index}>
<button
onClick={() => toggleColor(item)}
className={active[item] ? "active" : ""}
>
{item}
</button>
</li>
));
}
toggleColor sets value for active, and it specify that active should always be in the format of {About: true}, {Skills: true} and such. The !!! covers the case when certain keys are not existing in the object.
const toggleColor = function (item) {
setActive((prev) => {
return { [item]: !!!prev[item] };
});
};
Below is the full example, it runs in the snippet for convenience.
function Header() {
const [active, setActive] = React.useState({ About: true });
const itemList = ["About", "Skills", "Projects", "Words"];
const toggleColor = function (item) {
// on load, 'About' button has active class
// when clicking another menu item add active class, remove active from the rest of buttons
setActive((prev) => {
return { [item]: !!!prev[item] };
});
};
return (
<header className="header-img-container">
<nav>
<ul>
{itemList.map((item, index) => (
<li key={index}>
<button
onClick={() => toggleColor(item)}
className={active[item] ? "active" : ""}
>
{item}
</button>
</li>
))}
</ul>
</nav>
</header>
);
}
const App = () => {
return (
<div>
<Header />
</div>
);
};
ReactDOM.render(<App />, document.querySelector("#root"));
.App {
font-family: sans-serif;
text-align: center;
}
button {
padding: 6px;
}
.active {
border: 1px solid pink;
color: hotpink;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.production.min.js"></script>
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;
}
I am trying to create react app and i want overflow to hidden when button is pressed,
i want to display contact form on modal but overflow is running everything i can scroll even with modal is open
Here is my navbar with button
import React from "react";
import { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { FaBars, FaTimes } from "react-icons/fa";
import "./Navbar.css";
import { IconContext } from "react-icons/lib";
import Button from "./Button";
import Modal from "./Contact Form/Modal";
import { motion, AnimatePresence } from "framer-motion";
export default function Navbar() {
const [click, setClick] = useState(false);
const [button, setButton] = useState(true);
const [modalOpen, setModalOpen] = useState(false);
function closeModal() {
setModalOpen(false);
}
function openModal() {
setModalOpen(true);
}
function handleClick() {
setClick(!click);
}
function closeMobileMenu() {
setClick(false);
}
function showButton() {
if (window.innerWidth <= 960) {
setButton(false);
} else {
setButton(true);
}
}
function closeMobileMenu() {
setClick(false);
}
useEffect(() => {
showButton();
}, []);
window.addEventListener("resize", showButton);
return (
<>
<IconContext.Provider value={{ color: "#fff" }}>
<div className="navbar">
<div className="navbar-container container">
<Link to="/" className="navbar-logo" onClick={closeMobileMenu}>
LOGO
</Link>
<div className="menu-icon" onClick={handleClick}>
{click ? <FaTimes /> : <FaBars />}
</div>
<ul className={click ? "nav-menu active" : "nav-menu"}>
<li className="nav-item">
<Link to="/" className="nav-links" onClick={closeMobileMenu}>
Home
</Link>
</li>
<li className="nav-item">
<Link to="/" className="nav-links" onClick={closeMobileMenu}>
About Us
</Link>
</li>
<li className="nav-item">
<Link to="/" className="nav-links" onClick={closeMobileMenu}>
Contact Us
</Link>
</li>
{/* Main button */}
<li className="nav-btn">
{button ? (
<Link to='' className="btn-link">
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
className="btn--outline"
onClick={() => (modalOpen ? closeModal() : openModal())} //modal opens
>
CONTACT US
</motion.button>
</Link>
) : (
<Link
to=""
className="btn-link"
onClick={closeMobileMenu}
>
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.9 }}
className="btn--mobile"
buttonSize='btn--mobile'
buttonStyle='btn--outline'
onClick={() => {(modalOpen ? closeModal() : openModal())}} //modal opens
>
Contact US
</motion.button>
</Link>
)}
</li>
</ul>
</div>
</div>
<AnimatePresence
// Disable any initial animations on children that
// are present when the component is first rendered
initial={false}
// Only render one component at a time.
// The exiting component will finish its exit
// animation before entering component is rendered
exitBeforeEnter={true}
// Fires when all exiting nodes have completed animating out
onExitComplete={() => null}
>
{modalOpen && <Modal modalOpen={modalOpen} handleClose={closeModal} />}
</AnimatePresence>
</IconContext.Provider>
</>
);
}
I was trying to do it use State but it didn't work. I use style effect but i didn't manage to achieve it
You will make a boolean state with an initial value set to false.
When the button is clicked you will update the state from false to true and I will recommend it for you instead of making it true. then you will use this state easily with your style property and do what you need.
change the style bellow based on your needs.
import { useState } from "react";
export default function App() {
const [clicked, setClicked] = useState(false);
return (
<div className="App">
<h1 style={{ display: clicked ? "none" : "block" }}>Hello
CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={() => setClicked(!clicked)}>click</button> <= here instead of making it true. I made it the oppesite of the previous value. to toggle between them.
</div>
);
}
I am using react bootstrap table to show my data. The table is not responsive and has a over-proportioned size on the right side.
Look also at the picture showing that the table is much larger than the other components.
I have tried to include a few css elements such as container, width, max-width, among others however nothing worked.
I am importing the Bootstrap CSS using this: import 'bootstrap/dist/css/bootstrap.min.css';
Thanks in advance.
index.jsx
import React from 'react'
import '../../../../src/styles.css'
export default function Datatable({ data }) {
const columns = data[0] && Object.keys(data[0]);
return (
<table class="table" >
<thead class=" table-striped table-bordered table-sm ">
<tr >{data[0] && columns.map((heading) => <th>{heading}</th>)}</tr>
</thead>
<tbody class=" table-striped table-bordered table-sm " >
{data.map((row) => (
<tr>
{ columns.map((column) => (
<td>{row[column]}</td>
))}
</tr>
))}
</tbody>
</table>
);
}
styles.css
body {
background: #fafafa;
}
table {
background: #f89c9c;
font-size: 14px;
text-align: center;
}
thead {
font-size: 20px;
}
Base.js
import React from 'react';
import Menu from "./Menu"
import Button from "react-bootstrap/Button";
import Container from "react-bootstrap/container";
import Row from "react-bootstrap/row";
const Base = ({
title = "My Title",
description = "My description",
className = "",
children
}) => {
return (
<div>
<Menu />
<Container fluid className="bg-light" >
<Container fluid >
<div className="col bg-light text-dark text-left pt-5" >
<Row >
<h2 className="col-9 display-4 ml-0 font-weight-bold">{title}</h2>
<Button variant="link" className=" btn bg-light text-dark font-weight-bold">Investor</Button>
<Button variant="link" className="btn bg-light text-dark font-weight-bold">Borrower</Button>
<Button variant="link" className=" btn bg-light text-dark font-weight-bold">Charity</Button>
</Row>
<p className=" lead ml-0 font-weight-bold">{description}</p>
</div>
</Container>
<div className={className}>{children}</div>
</Container >
<footer className="footer bg-dark mt-auto py-3">
UserDashboard.js
import React, {useState, useEffect} from 'react';
import Base from '../core/Base'
import './helper/EnhancedTable';
import { Dash } from './helper/EnhancedTable'
const UserDashboard = () => {
return (
<Base title="User dashboard">
<Dash ></Dash>
</Base>
)
}
export default UserDashboard;
Table.js
import {API} from "../../backend"
import React, {useState, useEffect} from 'react';
import Datatable from './datatable';
require("es6-promise").polyfill();
require("isomorphic-fetch");
export default function Dash() {
const [data, setData] = useState([]);
//now we create the quesry state
const [q, setQ] = useState("");
const [searchColumns, setSearchColumns] = useState(["description", "borrower_name"]);
//this is the function that we want tpo fire when the dependencies are triggered
useEffect(() => {
//fetch will make the call to the server
fetch(`${API}project/`, {method: "GET"})
//then response will handle answer from server transforming the HTTP data into JSON data
.then((response) => response.json())
//now that we access to the JSON data from server we will get if from the local storage
.then((json) => setData(json))
}, []);
function search(rows) {
return rows.filter(
(row ) =>
searchColumns.some(column => row[column].toString().toLowerCase().indexOf(q.toLowerCase()) > -1
)
);
}
const columns = data[0] && Object.keys(data[0])
return (
<div>
<input type="text" value={q} onChange={(e) => setQ(e.target.value) }/>
{
columns && columns.map(column =>
<label>
<input
type="checkbox"
checked={searchColumns.includes(column)}
onChange={(e) => {
const checked = searchColumns.includes(column);
setSearchColumns((prev) => checked
? prev.filter((sc) => sc !== column)
: [...prev, column]
);
}}
/>
{column}
</label>)
}
<Datatable data={search(data)} />
</div>
)
}
export {Dash};