I have a project where I'm mapping out an array with a like-button within the mapped out div.
This button should work only for the specific parent div - at the moment it toggles everything.
In my code, I tried to do it the long way around with a switch (it did not work, and also not good). I tried to look this up in various ways.
I think I need to work with e.target, but I'm not sure how to translate e.target.value to a state. For example - if I push button with value 5 (in div 5) I want the showDiv-state to take in the value (showDiv{5}) and be set to true.
What am I missing here?
import { useState} from "react";
import { BulletinBoard } from "./BulletinBoard";
import PostLiked from "./PostLiked";
const ReactPost = () => {
const [showDiv, setShowDiv] = useState(false);
const [showDiv2, setShowDiv2] = useState(false);
const [showDiv3, setShowDiv3] = useState(false);
const [showDiv4, setShowDiv4] = useState(false);
const [showDiv5, setShowDiv5] = useState(false);
const [likeButton, setLikeButton] = useState(true);
const pickAndShow= (e) => {
e.preventDefault();
const chosenItem = e.currentTarget.value;
switch(parseInt(chosenItem)){
case 1:
console.log("Ett")
setShowDiv1(true);
setLikeButton(false);
case 2:
console.log("Två")
setShowDiv2(true);
setLikeButton(false);
break;
case 3:
console.log("Tre")
setShowDiv3(true);
setLikeButton(false);
break;
case 4:
console.log("Fyra")
setShowDiv4(true);
setLikeButton(false);
break;
case 5:
console.log("Fem")
setShowDiv5(true);
setLikeButton(false);
break;
default:
console.log("Error")
}
}
}
return (
<div className="grid">
{BulletinBoard.map((item) => (
<div className="grid-item"
key={item.id}>
<span className="row">
<p>Fråga #{item.id}</p>
<h2>{item.question}</h2>
</span>
<h3>{item.answer}</h3>
<div
className={`wrapper__${item.id}`}
>
{!showDiv ? (
<button
className="likebutton"
value={item.id}
onClick={pickAndShow}
> </button>
<div data-key={0 + item.id}>
{showDiv1 ?
<PostLiked/>
enter code here
:null }
</div>
</div>
</div>
))}
</div>
);
}
export default ReactPost;
EDIT: Here is a picture of what is happening now:
enter image description here
When the checkbox is clicked, every div within the mapped divs change:
enter image description here
Instead of having 5 showDiv state properties, you can have a single shownDiv property with a number value.
setShownDiv(parseInt(evt.currentTarget.value));
Related
I wanted to adapt this code show that, for example if you hovered over a specific , then the relating would also show. useState seems to be the only way to make this work in React as I tried a different example with eventlistner which crashed the page.
const Showstuff = () => {
const [isHovering, setIsHovering] = useState(false);
const handleMouseOver = () => {
setIsHovering(true);
};
const handleMouseOut = () => {
setIsHovering(false);
};
return(
<div>
<div onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>
Hover over div #1 here
</div><br /><br />
<div>
Hover over div #2 here
</div>
{isHovering && (
<div>
<h2>Text here visible when hovering div 1</h2>
</div>
)}
</div>
)
};
export default Showstuff;
I made multiple useStates for each items as a work around, but this means there's 3x const lines for each item I want to add, and I have 6 elements to hover. Can this be combined into a shorter code? I also tried:
const el = document.getElementById('container');
const hiddenDiv = document.getElementById('hidden-div');
el.addEventListener('mouseover', function handleMouseOver() {
hiddenDiv.style.visibility = 'visible';
});
el.addEventListener('mouseout', function handleMouseOut() {
hiddenDiv.style.visibility = 'hidden';
});
from a guide on bobbyhadz website but this would require the same idea of making multiple lines of the same code with different names. This works immediately after saving the page in vscode but then shortly afterwards crashes the page, and does not work - I assume it is not React compatible.
I would do something like this :
function App() {
const [isHovered, setIsHovered] = useState(null)
const handleMouseOver = (e) => {
switch (e.target.id) {
case "1":
setIsHovered(1)
break
case "2":
setIsHovered(2)
break
}
}
return (
<div className="App">
<div id="1" onMouseOver={handleMouseOver} onMouseOut={() => setIsHovered(null)}>
DIV 1
</div>
<div id="2" onMouseOver={handleMouseOver} onMouseOut={() => setIsHovered(null)}>
DIV 2
</div>
{isHovered && <h2>{isHovered === 1 ? "Div 1 is hovered" : "Div 2 is hovered"}</h2>}
</div>
)
}
That way you only use one useState hook and set the value of isHovered depending on the targetted div's id.
Instead of having isHovering be a boolean, make it something else. If your design means you can only hover one thing at a time, the simplest solution is to make isHovering just hold some ID. But if you have overlapping elements where it's possible to hover multiple at once, you can use an array of IDs, or an object where each key is an ID and each value is a boolean.
You need to modify your onMouseOver (and, possibly, onMouseOut) function(s) to pass an ID as an argument.
Here is a simple example:
const Showstuff = () => {
const [isHovering, setIsHovering] = useState();
const handleMouseOver = (id) => setIsHovering(id);
const handleMouseOut = () => setIsHovering();
return (
<div>
{[1, 2, 3, 4, 5, 6].map((n) => (
<>
<div
onMouseOver={() => handleMouseOver(n)}
onMouseOut={handleMouseOut}
>
{`Hover over div #${n} here`}
</div>
</>
))}
{isHovering && (
<div>
<h2>{`Text here visible when hovering div ${isHovering}`}</h2>
</div>
)}
</div>
);
};
You don't have to use a map function if that won't work for you. That's just what I'm doing in this example. Just make sure your IDs are unique.
If you need to be able to hover multiple items at once, you'll have to modify the handleMouseOver and handleMouseOut functions. For example, if you wanted to store the values in an array, you can do something like this:
const handleMouseOver = (id) =>
setIsHovering((oldIsHovering) => [...oldIsHovering, id]);
const handleMouseOut = (id) =>
setIsHovering((oldIsHovering) => oldIsHovering.filter((n) => n !== id));
You can use an array as a state variable and map over it:
export default function App() {
const [isHovering, setIsHovering] = useState(new Array(4).fill(false));
function handleMouseEnter(i) {
setIsHovering((prev) => {
const next = [...prev];
next[i] = true;
return next;
});
}
function handleMouseLeave(i) {
setIsHovering((prev) => {
const next = [...prev];
next[i] = false;
return next;
});
}
return (
<>
{isHovering.map((_, i) => (
<span
onMouseEnter={() => handleMouseEnter(i)}
onMouseLeave={() => handleMouseLeave(i)}
></span>
))}
{isHovering.map((v, i) => (
<p>
Hovering on {i}: {v.toString()}
</p>
))}
</>
);
}
https://stackblitz.com/edit/react-ts-owprrr?file=App.tsx
This is good if the HTML elements are the same. If all your elements are unique, you are better off using multiple states and naming them uniquely. You'll just end up making the design more confusing by trying to save a few lines of code.
I have 5 div's and 5 buttons. On each button clicked one div become visible. the other four gets hidden. I just want to ask is there any other better way to do it. Give suggestion as much as possible. Thank you!
let id1 = React.createRef()
let id2 = React.createRef()
let id3 = React.createRef()
let id4 = React.createRef()
let id5 = React.createRef()
function iid1() {
id1.current.classList.remove('hidden')
id1.current.classList.add('contents')
id2.current.classList.add('hidden')
id3.current.classList.add('hidden')
id4.current.classList.add('hidden')
id5.current.classList.add('hidden')
}
function iid2() {
id1.current.classList.add('hidden')
id2.current.classList.remove('hidden')
id2.current.classList.add('contents')
id3.current.classList.add('hidden')
id4.current.classList.add('hidden')
id5.current.classList.add('hidden')
}
function iid3() {
id1.current.classList.add('hidden')
id2.current.classList.add('hidden')
id3.current.classList.remove('hidden')
id3.current.classList.add('contents')
id4.current.classList.add('hidden')
id5.current.classList.add('hidden')
}
function iid4() {
id1.current.classList.add('hidden')
id2.current.classList.add('hidden')
id3.current.classList.add('hidden')
id4.current.classList.remove('hidden')
id4.current.classList.add('contents')
id5.current.classList.add('hidden')
}
function iid5() {
id1.current.classList.add('hidden')
id2.current.classList.add('hidden')
id3.current.classList.add('hidden')
id4.current.classList.add('hidden')
id5.current.classList.remove('hidden')
id5.current.classList.add('contents')
}
I just want the above code to be more efficient & readable. I'm looking for best practices for javascript. You can also tell me you would you solve this problem. I'm not looking for answer's. I'm here to seek best practices,
Thank you.
Use state to identify which div is the selected one. Buttons will change the state and your app will re-render adjusting the classNames for the divs.
const App = () => {
const [selected,setSelected] = React.useState(0);
const DIV_IDS = [0,1,2,3,4,5];
const selectItems = DIV_IDS.map((item) => {
return(
<button onClick={() => setSelected(item)}>{item}</button>
);
});
const divItems = DIV_IDS.map((item) => {
return (
<div key={item} className={selected === item ? 'visible' : 'hidden'}>
I am div {item}
</div>
);
});
return(
<div>
<div>{selectItems}</div>
<div>{divItems}</div>
</div>
);
};
ReactDOM.render(<App/>, document.getElementById('root'));
.hidden {
visibility: hidden;
}
.visible {
visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
May be best to just have the class in your JSX element classes. Something like:
<element className={(condition_for_shown) ? 'contents' : 'hidden'}>
...
</element>
and then for each button would be:
<button type="button" onClick={() => setStateConditonToSomething}>
...
</button>
Note that you'll need to store the condition in react state with useState or however you wanna store it.
The way i'd do it is -
const DivHidingComponent = ({ elementCount = 5 }) => { // element count defaults to 5
const [visibilityIndex, setVisibilityIndex] = useState(0);
const onClickCallback = useCallback((index) => () => {
setVisibilityIndex(index);
})
const buttonGroup = useMemo(() => {
const buttonGroup = [];
for (let i = 0; i < elementCount; i++) {
buttonGroup.push(
<button key={`${i}-button`} onClick={onClickCallback(i)} />
)
}
return buttonGroup;
}, [elementCount])
// only re-runs on a button click
const divGroup = useMemo(() => {
const divGroup = [];
for (let i = 0; i < elementCount; i++) {
divGroup.push(
<div key={`${i}-div`} style={{ visibility: visibilityIndex === i ? 'visible' : 'hidden' }} />
);
}
return divGroup;
}, [visibilityIndex]);
return (
<div>
<div>
{buttonGroup}
</div>
<div>
{divGroup}
</div>
</div>
);
}
I set the style directly in the div group loop, but you could assign a class name or go about setting the style however you want.
Div's visibility is set by the visibility index that is driven by the buttons being clicked on.
I passed the elementCount variable in the props so you could scale this to however many elements you want. 5 or a 1000. I assigned elementCount a value of 5 that will act as a default for when no value is passed when the component is initialized.
Also, you could drop the useMemo and useCallback hooks and it would still execute fine. But it would help improve performance if you say, set the element count to 10,000. With those hooks in place it'd only re-build the div group on re-render. That'd be the difference between running the loops 20k times (10k for buttons, 10k for divs).
I added the last paragraph incase you were not aware of React Hooks!
I hope this helps!
I want to change the count by one and make the same button revert back to its previous state on click.
export const CountButton = () => {
previousState = 100;
const [count, setCount] = useState(false);
return(
<div>
<button onClick={() => setCount(!count)}>Click Me!</button>
<div>{count ? previousState + 1 : previousState }</div>
</div>
)
}
This code will increase the vote by one and then revert on the second click.
I want my code to toggle a person handler, Before it was working but since I split into components, It seem to have broken.
Toggle happens on button click (see inside return statement <
button className={btnClass}
onClick={props.toggler}>Button</button>
Here is my entire cockpit.js file (inside src/components/cockpit/cockpit.js).
import React from 'react';
import classes from './cockpit.css';
const Ccockpit = (props) => {
const assignedClasses = [];
let btnClass = ''
if (props.cocPersonState) {
btnClass = classes.red;
console.log(".......")
}
if (props.cocperson <= 2) {
assignedClasses.push(classes.red)
}
if (props.cocperson <= 1) {
assignedClasses.push(classes.bold)
}
return(
<div className={classes.cockpit}>
<h1> Hi I am react App</h1>
<p className={assignedClasses.join(' ')}>hey </p>
<button className={btnClass}
onClick={props.toggler}>Button</button>
</div>
);
}
export default Ccockpit;
and inside App.js
return (
<div className={classes.App}>
<Ccockpit>
cocPersonState = {this.state.showPerson}
cocperson = {this.state.person.length}
toggler = {this.togglerPersonHandler}
</Ccockpit>
{person}
</div>
)
}
}
and this is my togglerpersonHandler code.
togglerPersonHandler = () => {
const doesShow = this.state.showPerson;
this.setState({
showPerson: !doesShow
});
}
I can't see to figure out that why it won't toggle and console.log/change color to red (It isn't changing the state). Can someone please review and figure out the mistake?
Your JSX still isn't right. Please review the JSX syntax with regards to giving it props/children.
You have this:
<Ccockpit>
cocPersonState = {this.state.showPerson}
cocperson = {this.state.person.length}
toggler = {this.togglerPersonHandler}
</Ccockpit>
But those values aren't children, they're properties. So they need to be in the opening tag, like this:
<Ccockpit
cocPersonState = {this.state.showPerson}
cocperson = {this.state.person.length}
toggler = {this.togglerPersonHandler}/>
Revisit some React tutorials to see how JSX should be structured and how it works.
Basically, I'm trying to clone an element and change its aria-label within React.cloneElement. I've got a component - ButtonArrows - that creates two Button components, one with an arrow icon pointing left, and one pointing right. I'd like to be able to programmatically change the aria-label, but the hyphen throws an error.
Here's some code showing what I'm trying to do:
const ButtonArrows = ({leftArrow, rightArrow, ...props})
const prevButton = (
<Button
aria-label="Previous",
icon={leftArrow}
/>
);
const nextButton = React.cloneElement(prevButton, {
//this is where the problem is:
aria-label="Next",
icon={rightArrow}
});
return(<div {...props}>{prevButton}{nextButton}</div>);
}
and obviously I can't do aria-label="Next" because of the hyphen.
Any suggestions? React unfortunately doesn't have anything like htmlFor (to stand in for html-for) when it comest to aria labels. Should I just put an ariaLabel prop on Button and pass it down, or is there a way to do it directly with cloneElement that I'm missing?
You should be able to use a plain JavaScript object here:
const nextButton = React.cloneElement(prevButton, {
'aria-label': 'Next',
icon: rightArrow
});
const ButtonArrows = ({leftArrow, rightArrow, ...props})
const prevButton = (
<Button
ariaLabel="Previous",
icon={leftArrow}
/>
);
const nextButton = React.cloneElement(prevButton, {
//this is where the problem is:
ariaLabelledby="Next",
icon={rightArrow}
});
return(<div {...props}>{prevButton}{nextButton}</div>);
}
change aria-label to ariaLabel