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>
Related
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 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;
}
How to set arrow style the same as the popper
import React from "react";
import ReactDOM from "react-dom";
import { Manager, Reference, Popper } from "react-popper";
function App() {
return (
<Manager>
<Reference>
{({ ref }) => (
<button type="button" ref={ref}>
Reference element
</button>
)}
</Reference>
<Popper placement="right">
{({ ref, style, placement, arrowProps }) => (
<div
ref={ref}
style={style}
className={`popover show bs-popover-${"right"}`}
>
<div className="popover-inner bg-primary">Popper element</div>
<div
className="arrow bg-primary"
ref={arrowProps.ref}
style={arrowProps.style}
/>
</div>
)}
</Popper>
</Manager>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
Code Sandbox: https://codesandbox.io/s/bold-shape-lomrm
First, add this CSS:
.bs-popover-auto[x-placement^=right] .arrow::after, .bs-popover-right .arrow::after {
border-right-color: #007bff;
}
Get rid of bg-primary class from the .arrow and give this style:
style="top: -2px;"
Preview
Demo: https://codesandbox.io/s/eager-wu-h337q
I need to be able to hide components that gets wrapped because it goes over the max width.
<div style={{width:100}}>
<div style={{width:50}}>
component1
</div>
<div style={{width:50}}>
component2
</div>
<div style={{width:50}}>
component3
</div>
</div>
//But I actually use map to render children
<div style={{width:100}}>
{components.map((item, index) => {
return <div style={{width:50}}>component{index + 1}</div>)
}}
</div>
as shown in the code above, the parent div is of with 100. So the last component (component3) would go over the width of the parent by 50px and will be rendered in the second line. However, I want any component that leaves the first line to be not rendered at all. How do I make sure that only component1 and component2 shows and excludes component3?
You could add up the widths of all the components in a separate variable, and render null for all components remaining after the total width of those already rendered exceeds 100.
Example
class App extends React.Component {
state = {
components: [{ width: 50 }, { width: 50 }, { width: 50 }]
};
render() {
const { components } = this.state;
let totalWidth = 0;
return (
<div style={{ width: 100 }}>
{components.map((item, index) => {
totalWidth += item.width;
if (totalWidth > 100) {
return null;
}
return (
<div key={index} style={{ width: 50 }}>
component{index + 1}
</div>
);
})}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
I'm currently using the React Bootstrap Modal. I'm trying to center an element within a modal with flexbox, but having a lot of trouble doing just that. Below is my code, and how it currently looks.
import { Modal } from 'react-bootstrap'
import React from 'react';
import { Button } from 'react-bootstrap';
import * as welcome from '../../styles/welcome'
class Welcome extends React.Component{
constructor(props){
super(props)
this.state = {
showModal: true
}
this.close=this.close.bind(this)
this.open=this.open.bind(this)
}
componentWillReceiveProps(nextProps){
debugger
if(nextProps.modal_content !== this.props.modal_content){
this.setState({ showModal: true });
}
}
close(){
this.setState({ showModal: false });
}
open() {
this.setState({ showModal: true });
}
render() {
return (
<div>
<Modal style={welcome.welcomeBody} show={this.state.showModal} onHide={this.close}>
<div style={{display: 'flex', justifyContent: 'center'}}>
<div style={{backgroundColor: 'black', border: '1px solid black', borderRadius: '100%', width: '50px', height: '50px'}}></div>
</div>
</Modal>
</div>
);
}
}
export default Welcome
You are applying flex in the image to align it center...which is wrong...
Flex always be applied to the parent container so that its children items use the flex features.
Wrap your image in a div and then apply display:flex and justify-content:center to that div so that image will be aligned centered.
<div style={{display: 'flex',justifyContent: 'center'}}>
<img src="pic.png"></img>
</div>
<div style="display: flex;justify-content: center;">
<img src="http://via.placeholder.com/350x150">
</div>
Updated Code
<div style="display: flex;justify-content: center;">
<div style="background-color:black;border:1px solid;height:50px;width:50px;border-radius:50%;"></div>
</div>