React custom dropdown with event listener - javascript

I created a Dropdown that when I click outside of it the dropdown disappears. I used a click event listener to determine if I clicked outside the dropdown.
After a few clicks, the page slows down and crashes. Perhaps the state is being rendered in a loop or too many events are being fired at once?
How do I fix this?
Also, is there a more React way to determine if I clicked outside an element? (Instead of using a document.body event listener)
Here is the codepen:
const items = [
{
value: 'User1'
},
{
value: 'User2'
},
{
value: 'User3'
},
{
value: 'User4'
},
{
value: 'User5'
}
];
class Dropdown extends React.Component {
state = {
isActive: false,
}
render() {
const { isActive } = this.state;
document.addEventListener('click', (evt) => {
if (evt.target.closest('#dropdownContent')) {
//console.warn('clicked inside target do nothing');
return;
}
if (evt.target.closest('#dropdownHeader')) {
//console.warn('clicked the header toggle');
this.setState({isActive: !isActive});
}
//console.warn('clicked outside target');
if (isActive) {
this.setState({isActive: false});
}
});
return (
<div id="container">
<div id="dropdownHeader">select option</div>
{isActive && (
<div id="dropdownContent">
{items.map((item) => (
<div id="item" key={item.value}>
{item.value}
</div>
))}
</div>
)}
</div>
);
};
}
ReactDOM.render(
<Dropdown items={items} />,
document.getElementById('root')
);
#container {
position: relative;
height: 250px;
border: 1px solid black;
}
#dropdownHeader {
width: 100%;
max-width: 12em;
padding: 0.2em 0 0.2em 0.2em;
margin: 1em;
cursor: pointer;
box-shadow: 0 1px 4px 3px rgba(34, 36, 38, 0.15);
}
#dropdownContent {
display: flex;
flex-direction: column;
position: absolute;
top: 3em;
width: 100%;
max-width: 12em;
margin-left: 1em;
box-shadow: 0 1px 4px 0 rgba(34, 36, 38, 0.15);
padding: 0.2em;
}
#item {
font-size: 12px;
font-weight: 500;
padding: 0.75em 1em 0.75em 2em;
cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root">
<!-- This element's contents will be replaced with your component. -->
</div>

There's a pretty simple explanation for what you're experiencing. :)
The way I was able to figure it out was the number of warnings that were showing up in the terminal every time I clicked somewhere was getting higher and higher, especially when the state changed.
The answer though is that since you were adding the event listener code in the render function, every time the code re-rendered it would add more and more event listeners slowing down your code.
Basically the solution is that you should move the adding of event listeners to componentDidMount so it's only run once.
Updated working javascript:
const items = [
{
value: 'User1'
},
{
value: 'User2'
},
{
value: 'User3'
},
{
value: 'User4'
},
{
value: 'User5'
}
];
class Dropdown extends React.Component {
state = {
isActive: false,
}
// added component did mount here
componentDidMount(){
const { isActive } = this.state;
document.addEventListener('click', (evt) => {
if (evt.target.closest('#dropdownContent')) {
console.warn('clicked inside target do nothing');
return;
}
if (evt.target.closest('#dropdownHeader')) {
console.warn('clicked the header toggle');
this.setState({isActive: !isActive});
}
console.warn('clicked outside target');
if (isActive) {
this.setState({isActive: false});
}
});
}
render() {
const { isActive } = this.state;
//removed event listener here
return (
<div id="container">
<div id="dropdownHeader">select option</div>
{isActive && (
<div id="dropdownContent">
{items.map((item) => (
<div id="item" key={item.value}>
{item.value}
</div>
))}
</div>
)}
</div>
);
};
}
ReactDOM.render(
<Dropdown items={items} />,
document.getElementById('root')
);

Related

How can I implement conditional rendering using map function?

I made 5 blocks and want to make the letters on each block thick when the mouse is hover. I made isHover state and changed the thickness of the writing according to the state, but the problem is that the thickness of all five changes. I think I can solve it by using conditional rendering, but I don't know how to use it. Of course, it can be implemented only with css, but I want to implement it with conditional rendering because I am practicing the code concisely.
import "./styles.css";
import styled from "styled-components";
import { useState } from "react";
export default function App() {
const array = [
{ id: "1", title: "ABC" },
{ id: "2", title: "DEF" },
{ id: "3", title: "GHI" },
{ id: "4", title: "JKL" },
{ id: "5", title: "MNO" }
];
const [isHover, setIsHover] = useState(false);
return (
<Head isHover={isHover}>
<div className="header">
{array.map((content, id) => {
return (
<div
className="header__title"
onMouseEnter={() => {
setIsHover(true);
}}
onMouseLeave={() => {
setIsHover(false);
}}
>
{content.title}
</div>
);
})}
</div>
</Head>
);
}
const Head = styled.div`
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
.header {
display: inline-flex;
border: 1px solid black;
box-sizing: border-box;
}
.header__title {
border: 1px solid red;
padding: 5px 10px;
font-weight: ${(props) => (props.isHover ? "700" : "400")};
}
`;
codesandbox
https://codesandbox.io/s/aged-cherry-53pr2r?file=/src/App.js:0-1170
The problem is that you are using the same state for all the 5 blocks. There are multiple approaches you could take to solve this problem.
1. Multiple states
You could create 5 different isHover<N> states (maybe a single one, but as an array)
2. Component extraction
You could just extract out a component for each entry in array and do state management in that component.
function App() {
const array = [...];
return (
<Head>
<div className="header">
{array.map((content, id) => (
<HeaderTitle key={content.id} content={content} />
)}
</div>
</Head>
);
}
function HeaderTitle({ content }) {
const [isHover, setIsHover] = useState(false);
return (
<StyledHeaderTitle
isHover={isHover}
onMouseEnter={() => setIsHover(true)}
onMouseLeave={() => setIsHover(false)}
>
{content.title}
</StyledHeaderTitle>
);
}
const StyledHeaderTitle = styled.div`
font-weight: ${(props) => (props.isHover ? "700" : "400")};
`
3. Using style prop
Directly apply the font weight using the style prop (An extension to approach 2)
function HeaderTitle({ content }) {
const [isHover, setIsHover] = useState(false);
return (
<StyledHeaderTitle
onMouseEnter={() => setIsHover(true)}
onMouseLeave={() => setIsHover(false)}
style={{ fontWeight: isHover ? "700" : "400" }}
>
{content.title}
</StyledHeaderTitle>
);
}
4. CSS
CSS already allows you to track hover states over different elements and you don't need to manually track it in javascript.
.header__title {
border: 1px solid red;
padding: 5px 10px;
font-weight: 400;
&:hover {
font-weight: 700;
}
}
There's no need to use React state and event listeners here, you can do it all in CSS instead:
.header__title {
border: 1px solid red;
padding: 5px 10px;
font-weight: 400;
}
.header__title:hover {
font-weight: 700;
}
Just add this pseudo class and you're good to go
.header__title:hover {
font-weight: 700;
}

Toggle state taking previous value in react?

I am trying to create a to-do list app. The basic functionality includes adding and deleting. So when a user selects one or multiple items, a delete button will appear and it will be deleted. My problem is I am implementing a toggle state which when a user clicks on todo item, it will be strikethrough( A strikethrough text decoration will be added via CSS).
The problem arises when I add two items. When I click on the first item , it gets a strike through and when I delete it, the first one goes but the second item gets the strike through this time.
The running sample in codesandbox. Just try adding two items and delete the first one. The second one also gets a strike through.
I believe its because the toggle state value is being remembered.
This is the Content.js component
import "./styles/content.css";
import Individual from "./Individual";
import { useEffect, useState } from "react";
import { updateItem, markIncomplete } from "./action/action";
const Contents = (props) => {
const items = useSelector((state) => state.todoReducer.items);
const dispatch = useDispatch();
const handleClick = (e, isComplete, content, id) => {
// console.log(isComplete);
if (isComplete === false) {
//evaluates false to true
const newobj = {
isComplete: true,
content,
id
};
dispatch(updateItem(newobj));
props.deletebutton(true);
} else {
const falseobj = {
isComplete: false,
content,
id
};
dispatch(markIncomplete(falseobj));
}
};
useEffect(() => {
console.log("statechanging of contents");
});
return (
<div className="content-ui">
<div>
{items.map((vals) => (
<Individual
vals={vals}
deletebutton={props.deletebutton}
handleClick={handleClick}
/>
))}
</div>
</div>
);
};
export default Contents;
This is the individual.js which deals with toggle function
import { useDispatch, useSelector } from "react-redux";
import "./styles/content.css";
import { updateItem, markIncomplete } from "./action/action";
const Individual = (props) => {
console.log("child" + props.vals.isComplete);
const [toggle, isToggled] = useState(false);
const handleToggle = () => {
const mytoggle = !toggle;
isToggled(mytoggle);
};
return (
<div>
<div
className={toggle ? "toggled" : "card-elements"}
onMouseDown={handleToggle}
onClick={(e) => {
props.handleClick(
e,
props.vals.isComplete,
props.vals.content,
props.vals.id
);
handleToggle;
}}
>
{props.vals.content}
</div>
</div>
);
};
export default Individual;
Css of toggler
.toggled {
/* border: 1px solid rgb(94, 94, 94); */
box-shadow: rgba(0, 0, 0, 0.05) 0px 0px 0px 1px;
text-align: left;
box-sizing: border-box;
padding: 10px 3px 10px 7px;
margin-top: 4px;
margin-bottom: 8px;
border-radius: 5px;
background-color: white;
font-size: 12px;
font-family: "Roboto ", monospace;
text-decoration: line-through;
}
.card-elements {
/* border: 1px solid rgb(94, 94, 94); */
box-shadow: rgba(0, 0, 0, 0.05) 0px 0px 0px 1px;
text-align: left;
box-sizing: border-box;
padding: 10px 3px 10px 7px;
margin-top: 4px;
margin-bottom: 8px;
border-radius: 5px;
background-color: white;
font-size: 12px;
font-family: "Roboto ", monospace;
}
You need to add keys to your mapped items (there should also be a warning about this in the console).
Keys help React identify which items have changed, are added, or are removed.
As is stated from React's documents.
return (
<div className="content-ui">
<div>
{items.map((vals) => (
<Individual
key={vals.id} // <-- add unique key
vals={vals}
deletebutton={props.deletebutton}
handleClick={handleClick}
/>
))}
</div>
</div>
);

ReactJS - pass object keys and values as props to div

In my Class component Field.jsx render(), I'm expanding my <Position> component using <Flipper>, (an abstracted flip animation), like so:
import { Flipper, Flipped } from 'react-flip-toolkit'
import { Position } from "./Position";
import "./css/Position.css";
class Field extends Component {
constructor(props) {
super(props);
this.state = {
fullScreen: false,
};
}
toggleFullScreen() {
this.setState({ fullScreen: !this.state.fullScreen });
}
...
render() {
const { players } = this.props;
const { fullScreen } = this.state;
if(players){
return (
<div className="back">
<div className="field-wrapper" >
<Output output={this.props.strategy} />
<Flipper flipKey={fullScreen}>
<Flipped flipId="player">
<div className="field-row">
{this.getPlayersByPosition(players, 5).map((player,i) => (
<Position
key={i}
className={fullScreen ? "full-screen-player" : "player"}
getPositionData={this.getPositionData}
toggleFullScreen={this.toggleFullScreen.bind(this)}
>{player.name}</Position>
))}
</div>
</Flipped>
</Flipper>
</div>
</div>
);
}else{
return null}
}
When I render it, I get clickable items from the mapped function getPlayersByPosition(), like so:
And if I click on each item, it expands to a div with player name:
Which is passed as props.children at component <div>
Position.jsx
import React from "react";
import "./css/Position.css";
export const Position = props => (
<div
className={props.className}
onClick={() => {
props.getPositionData(props.children);
props.toggleFullScreen();
console.log(props.getPositionData(props.children))
}}
>
{props.children}
</div>
);
getPositionData(), however, returns an object with many items on its turn, as seen by console above:
{matches: 7, mean: 6.15, price: 9.46, value: 0.67, G: 3, …}
QUESTION:
How do I pass and print theses other props keys and values on the expanded purple div as text?, so as to end with:
Patrick de Paula
matches: 7
mean: 6.15
price:9.46
....
NOTE:
Position.css
.position-wrapper {
height: 4em;
display: flex;
justify-content: center;
align-items: center;
font-weight: lighter;
font-size: 1.4em;
color: #888888;
flex: 1;
/*outline: 1px solid #888888;*/
}
.player {
height: 4em;
width: 4em;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
font-weight: lighter;
font-size: 1.4em;
/*background-color: #66CD00;*/
color: #ffffff;
}
.full-screen-player {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
cursor: pointer;
background-image: linear-gradient(
45deg,
rgb(121, 113, 234),
rgb(97, 71, 182)
);
}
Looks like the props are all set & ready to be print as seen on your console. You can access them via props.getPositionData(props.children).property_name_here or destructure them
export const Position = props => {
const { matches, mean, price } = props.getPositionData(props.children);
return (
<div
className={props.className}
onClick={() => {
props.getPositionData(props.children);
props.toggleFullScreen();
console.log(props.getPositionData(props.children))
}}
>
<p>Name: {props.children}</p>
<p>Matches: {matches}</p>
<p>Mean: {mean}</p>
<p>Price: {price}</p>
</div>
)
}
Regarding the issue on the fullScreen prop (see comments section):
Is there a way to print them ONLY after toggleFullScreen()
Since you already have a state on the Field component which holds your fullScreen value, on your Field component, you need to pass the fullScreen prop as well to the Position component. e.g., fullScreen={this.state.fullScreen}. Back on Position component, have some condition statements when you are rendering.
Example:
<>
{props.fullScreen &&
<p>Name: {props.children}</p>
}
</>

resizing divs on click

I've been trying to add a onClick event to the divs which will resize a div to fullscreen when clicking on that div but when I click on a div, all the div are getting expanded. How do I restrict that onClick event to only a single a div and make that single div resize to full screen? I've also added transition so that when it resize to fullscreen, it looks like a animation but all the divs have been affected by it when clicking on just a single div
import React from "react";
import "./styles.scss";
const colors = [
"palevioletred",
"red",
"green",
"blue",
"yellow",
"orange",
"lightblue"
];
const randomColor = items => {
return items[randomHeight(0, items.length)];
};
const randomHeight = (min, max) => {
return Math.floor(min + Math.random() * (max - min + 1));
};
export default class App extends React.Component {
constructor(props) {
super(props);
this.addActiveClass = this.addActiveClass.bind(this);
this.state = {
active: false
};
}
addActiveClass() {
const currentState = this.state.active;
this.setState({ active: !currentState });
}
render() {
return (
<div class="container">
{Array.from({ length: 30 }).map((item, index) => (
<div
key={index}
style={{
background: randomColor(colors),
height: randomHeight(100, 200)
}}
className={this.state.active ? "full" : null}
onClick={this.addActiveClass}
/>
))}
</div>
);
}
}
* {
box-sizing: border-box;
}
body {
margin: 40px;
background-color: #fff;
color: #444;
font: 2em Sansita, sans-serif;
}
.container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
max-height: 100vh;
}
.container > * {
border: 2px solid orange;
border-radius: 5px;
margin: 10px;
padding: 10px 20px;
background-color: red;
color: #fff;
}
.full{
width: 100%;
height: 100%;
transition: 2s;
}
codesandbox
Currently you're sharing one state with all of the divs. In order to resolve this problem, create activeIndex state, initialize it with -1 maybe, and use it like:
// ...
class App extends React.Component {
constructor(props) {
super(props);
this.addActiveClass = this.addActiveClass.bind(this);
this.state = {
activeIndex: -1
};
}
addActiveClass(activeIndex) {
this.setState(prev => ({
activeIndex: prev.activeIndex === activeIndex ? -1 : activeIndex
}));
}
render() {
return (
<div className="container">
{Array.from({ length: 30 }).map((item, index) => {
return (
<div
key={index}
style={{
background: randomColor(colors),
height: randomHeight(100, 200)
}}
className={this.state.activeIndex === index ? "full" : ""}
onClick={() => this.addActiveClass(index)}
/>
);
})}
</div>
);
}
}

How to create vertical tab using reactjs and css

Am trying to bulid vertical tab that will function exactly like in the demo link below
sample links from w3schools
here is the screenshot of what am trying to achieve as per the demo sample above
To this effect tried solution found here at but it does not give me what I want as per demo sample above
Stackoverflow link
Now I have decided to go my own way in trying it out.
I have succeeded in displaying the content from an array via reactjs. when user click on each country, the content
of that country gets displayed.
My Problem:
My issue is that I cannot get it to display the content in a vertical tab div as can be seen in the screenshot
Here is the coding so far
import React, { Component, Fragment } from "react";
import { render } from "react-dom";
class Country extends React.Component {
state = { open: false };
toggleOpen = id => {
alert(id);
this.setState(prevState => ({
open: !prevState.open
}));
};
render() {
return (
<React.Fragment>
<div key={this.props.data.id}>
<button onClick={() => this.toggleOpen(this.props.data.id)}>
{this.props.data.name}
</button>
</div>
<div>
{this.state.open && (
<div>
<div>
<b>id: </b>
{this.props.data.id}
</div>
<div>
<b>Info: </b>
{this.props.data.info}
</div>
<div>
<b>Country name:</b> {this.props.data.name}
</div>
content for <b> {this.props.data.name}</b> will appear here..
</div>
)}
</div>
</React.Fragment>
);
}
}
class VerticalTab extends React.Component {
constructor() {
super();
this.state = {
data: [
{ id: "1", name: "London", info: "London is the capital city of England." },
{ id: "2", name: "Paris", info: "Paris is the capital of France." },
{ id: "3", name: "Tokyo", info: "Tokyo is the capital of Japan." }
]
};
}
render() {
return (
<div>
<div>
{this.state.data.map(country => (
<Country key={country.id} data={country} />
))}
</div>
</div>
);
}
}
Is this what you are looking for?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
currentTab: -1,
data: [
{ id: "1", name: "London" ,info: "London is the capital city of England."},
{ id: "2", name: "Paris" ,info: "Paris is the capital of France." },
{ id: "3", name: "Tokyo" ,info: "Tokyo is the capital of Japan."}
]
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(currentTab) {
this.setState({ currentTab });
}
render() {
return (
<div>
<h2>Vertical Tabs</h2>
<p>Click on the buttons inside the tabbed menu:</p>
<div className="tab">
{this.state.data.map((button, i) => (
<button key={button.name} className="tablinks" onClick={() => this.handleClick(i)}>{button.name}</button>
)
)
}
</div>
<div className="tabcontent">
{this.state.currentTab !== -1 &&
<React.Fragment>
<h3>{this.state.data[this.state.currentTab].name}</h3>
<p>{this.state.data[this.state.currentTab].info}</p>
</React.Fragment>
}
</div>
</div>
)
}
}
ReactDOM.render( < App / > ,
document.getElementById('root')
);
* {box-sizing: border-box}
body {font-family: "Lato", sans-serif;}
/* Style the tab */
.tab {
float: left;
border: 1px solid #ccc;
background-color: #f1f1f1;
width: 30%;
height: 300px;
}
/* Style the buttons inside the tab */
.tab button {
display: block;
background-color: inherit;
color: black;
padding: 22px 16px;
width: 100%;
border: none;
outline: none;
text-align: left;
cursor: pointer;
transition: 0.3s;
font-size: 17px;
}
/* Change background color of buttons on hover */
.tab button:hover {
background-color: #ddd;
}
/* Create an active/current "tab button" class */
.tab button.active {
background-color: #ccc;
}
/* Style the tab content */
.tabcontent {
float: left;
padding: 0px 12px;
border: 1px solid #ccc;
width: 70%;
border-left: none;
height: 300px;
}
<script src="https://unpkg.com/react#16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js" crossorigin></script>
<div id="root" />
React Tabs with Hooks
Here is a link to react tabs. Maybe this will help you.
enter code here

Categories

Resources