I have a multi page form that renders a list of buttons for each possible answer.
I am currently using getElementByID to change the button style when a button is clicked. I think this is not considered good practice in react.
can I use the useRef hook to target the DOM element and change its style instead of using getElementByID if the buttons are dynamically displayed with map?
{answers.map((answer, count = 0) => {
return (
<Button
key={count}
id=`button${count}`
onClick={(e) => {
document.getElementById(`${e.currentTarget.id}`).style.color = "white";
}}
>
<ButtonTitle>{answer.name}</ButtonTitle>
</Button>
);
})}
(animations on safari are breaking the active style, so I can't use the active pseudo element)
You can do this by adding a new state and toggle active class by that state.
Code something like this.
const [activeindex, setActiveIndex] = useState("");
return(
<>
{answers.map((answer, count = 0) => {
return (
<Button
key={count}
className={count==activeindex?"acvie":""}
onClick={(e) => {
setActiveIndex(count)
}}
>
<ButtonTitle>{answer.name}</ButtonTitle>
</Button>
);
})}
}
</>
And use .active class in css file.
Related
I've implemented a drawer similar to the example shown here. For working reproductions, please follow the link above and edit the Responsive Drawer on Stackblitz or Codesandbox. All that needs to be done to see the issue is to add onClick={(e) => console.log(e.target.tagName)} to the <ListItem button>.
Everything works as expected, except if you click on the top/bottom edge of a ListItem - in that case, I'm not able to get to the value assigned to the ListItem, and it's treated like an escape/cancellation and closes the drawer. In the <ListItem> the method onClick={(e) => console.log(e.target.tagName) will correctly log SPAN if you click in the middle, but will log DIV and be unresponsive if you click on the edge.
Example of one of the list items:
<Collapse in = {isOpen} timeout = 'auto' unmountOnExit>
<List component = 'div' disablePadding>
<ListItem button key = {'Something'} value = {'Something'} sx = {{pl: 4}} onClick = {(e) => handleSelect(e)}>
<ListItemIcon><StarBorder /></ListItemIcon>
<ListItemText primary = {'Something'} />
</ListItem>
</List>
</Collapse>
Overall structure of the drawer:
<List>
<Box>
<ListItem />
<Collapse>
<ListItem />
<ListItem />
</Collapse>
</Box>
</List>
onClick:
const handleSelect = (e) =>
{
const parentTag = e.target.tagName
if (parentTag === 'DIV')
{
console.log(e.target.innerHTML)
for (let child of e.target.children)
{
if (child.tagName === 'SPAN')
{
console.log(child.innerHTML)
}
}
}
else if (parentTag === 'SPAN')
{
console.log(e.target.innerHTML)
}
}
If you were to click in the middle of a ListItem, then parentTag === 'SPAN', and the console will log Something as expected.
But if you click on the top or bottom edge, then parentTag === 'DIV', and console.log(e.target.innerHTML) will show the following:
<div class="MuiListItemIcon-root..."><svg class="MuiSvgIcon-root..."><path d="..."></path>
</svg></div><div class="MuiListItemText-root..."><span class="MuiTypography-root...">
Something
</span></div><span class="MuiTouchRipple-root..."><span class="css..."><span
class="MuiTouchRipple..."></span></span></span>
There are three <span> elements, and I need the value of the first. However, console.log(child.innerHTML) always logs the later ones:
<span class="css..."><span
class="MuiTouchRipple..."></span></span>
Is there a way to get to the actual value I need? Or a better way to handle this, maybe by making the <div> unclickable/expanding the click area of the ListItem?
We can traverse till topmost parent div and search the content span from there:
const handleSelect = (e) => {
let target = e.target;
// get to the parent
while (!target.classList.contains('MuiButtonBase-root')) {
target = target.parentElement;
}
// get the content span
target = target.querySelector('.MuiTypography-root');
// utilize the content
setContent(`Clicked on: ${selected.tagName}, content: ${target.innerHTML}`);
console.log(selected);
handleDrawerToggle();
};
Even if you click on svg path element, above code will get you to the desired span element.
demo on stackblitz.
Also, we can prevent clicks on parent div using pointer-events:none CSS rule. But this will create huge unclickable area. And the SVG icon is also clickable :/ We'll have to make a lot of changes in CSS to bring the desired span in front of/covering everything.
Old answer
If you are trying to figure out which item got clicked then you can define onclick handler like this:
<ListItem button key={text}
onClick={(e) => console.log(text) } >
OR
<ListItem button key={text}
onClick={(e) => handleSelect(text) } >
This will give you the list item name right away. Then you can open corresponding content.
That's actually a CSS problem. You need to make the child elements width and height equal to the parent elements width and height. This is true for every element which is inline by default and you want to work with it.
Here are some docs about the CSS box model:
box model
understanding the inline box model
In this case, you want to change the display element in ListItem to div
AKA
<ListItem component="div">
// some stuff
</ListItem>
I'm using the ant-design Dropdown component with a right click action inside.
I want to be able to increment by 5 or 10 at once. But whenever this is being clicked it will ignore the one by the onClick listener for the Menu.Item.
const App = () => {
const [counter, setCounter] = useState(1);
const menu = (
<Menu>
<Menu.Item key="five" onClick={() => setCounter(counter + 5)}>
by 5
</Menu.Item>
<Menu.Item key="ten" onClick={() => setCounter(counter + 10)}>
by 10
</Menu.Item>
</Menu>
);
return (
<div>
<p>Counter: {counter}</p>
<div onClick={() => setCounter(counter + 1)} style={STYLING}>
<p>Click here to increment</p>
<Dropdown overlay={menu} trigger={["contextMenu"]}>
<span>
Right click here for custom increment
</span>
</Dropdown>
</div>
</div>
);
};
Codesandbox example: https://codesandbox.io/s/contextmenu-with-dropdown-antd-n4c5i?file=/index.js
I have tried to play around with ReactDOM.createPortal, but I just can't figure out how to use it correctly in a scenario like this one.
I know I should probably not go into a createPortal solution, but the reason I need this is not for this simple example, but I want to have this functionality inside the ant-design table column header while also having sorting support.
I figured I don't need to use portals. Instead I can use stopPropagation to prevent any parent node to get a onClick event.
Within the Menu.Item onClick event the standard javascript event is available under a domEvent field.
So we can create a function like this:
const menuOnClick = (amount) => (e) => {
e.domEvent.stopPropagation();
setCounter(counter + amount);
};
and update our Menu.Item onClick callbacks to this
<Menu.Item key="five" onClick={menuOnClick(5)}>
Sandbox example: https://codesandbox.io/s/contextmenu-with-dropdown-antd-solution-8029o?file=/index.js
i want to improve my code, with several buttons that has custom class names (attr), when clicked should add to body tag (toggle), now is adding the first button only because for ("button")[0] but should work for each button
import React, { useState, useEffect } from "react"
function Test() {
const [isClass, setIsClass] = useState(false)
useEffect(() => {
const x = document.getElementsByTagName("button")[0].getAttribute("custom-class")
document.body.classList.toggle(x, isClass)
}, [isClass])
return (
<>
<button custom-class='test1' onClick={() => setIsClass(!isClass)}>
Setting test1 className
</button>
<button custom-class='test2' onClick={() => setIsClass(!isClass)}>
Setting test2 className
</button>
</>
)
}
export default Test
Thanks
Please use this code.
let oldStyle = "";
const handleClick = (index) => {
const x = [...document.getElementsByTagName("button")].map(value => value.getAttribute("custom-class"));
document.body.classList.contains(x[index]) ? document.body.classList.remove(x[index]) : document.body.classList.add(x[index]);
if(document.body.classList.length > 1) document.body.classList.replace(oldStyle, x[index]);
oldStyle = x[index];
}
return (
<>
<button custom-class='test1' onClick={() => handleClick(0)}>
Setting test1 className
</button>
<button custom-class='test2' onClick={() => handleClick(1)}>
Setting test2 className
</button>
</>
)
It is better not to use DOM querying and manipulation directly with elements that are created and controlled by react. In your particular example it is ok to use document.body, but not ok to search for buttons, especially when you try to find them by tag name. To actually toggle a class in classList you don't need second parameter in most cases, so additional state is also not needed.
React way to get reference to element renderend by React would be to use Ref. However, in your particular case side effect can be launched inside event handler, so you don't need useEffect or useRef.
Your onClick handler can accept event object that is Synthetic Event. It holds property target that holds reference to your button.
So, the easiest way would be simply to write like this:
function Test() {
function clickHandler(event) {
let classToToggle = event.target.getAttribute("custom-class");
document.body.classList.toggle(classToToggle);
}
return (
<>
<button key="test1" custom-class="test1" onClick={clickHandler}>
Setting test1 className
</button>
<button key="test2" custom-class="test2" onClick={clickHandler}>
Setting test2 className
</button>
</>
);
}
export default Test;
If you need to have only single className from the list, you can decide which class to enable or disable with a bit of a state. Since anything can add classes on body it might be useful to operate only on some set of classes and not remove everything.
Also, not mentioned before, but consider using data attribute as its purpose is to keep some additional data.
function Test() {
// this can come from props or be hardcoded depending on your requirements
// If you intend to change it in runtime, consider adding side effect to cleanup previous classes on body
let [classesList] = React.useState(["test1", "test2"]);
let [activeClass, setActiveClass] = React.useState("");
// You can switch actual classes in effect, if you want to
function clickHandler(event) {
let classToToggle = event.target.dataset.customClass;
// we remove all classes from body that are in our list
document.body.classList.remove(...classesList);
if (activeClass === classToToggle) {
setActiveClass("");
} else {
// if class not active - set new one
document.body.classList.add(classToToggle);
setActiveClass(classToToggle);
}
}
return (
<>
{classesList.map((cn) => (
<button key="cn" data-custom-class={cn} onClick={clickHandler}>
Setting {cn} className
</button>
))}
</>
);
}
I have a column list of elements, and each of them has hidden div, I want to show hidden element on click, but when I'm clicking another div, I want to hide current and show the one I clicked last, how can I do it correctly?
You could have two specific classes, one that hides element and one that shows element. when clicking on the element you can use jQuery or JavaScript to toggle the class that shows element for the hidden div of that specific element and hide everything for any other div.
The component you're rendering could take in an active prop and only render the second div if this prop is true.
With this, you could then keep track of which element is selected in the parent.
I threw together a working example with very simple content
import React, { useState } from 'react';
const ListItem = ({id, isActive, handleClick}) => {
return (
<div id={id} onClick={handleClick}>
Here is the element
{!!isActive && <div>I am the selected element</div>}
</div>
);
};
export const List = () => {
const [selectedItem, setSelectedItem] = useState();
const items = ['one', 'two', 'three'];
const handleClick = (event) => {
setSelectedItem(event.target.id);
}
return (
<div>
{items.map(item => (
<ListItem id={item} isActive={item===selectedItem} handleClick={handleClick}/>
))}
</div>
)
}
i am using a functional component, and have created a sidebar menu structure , with parent child way (kind of dropdown). So when I click on parent an active class should be toggle and on its next element toggle style> display> none/block.
<Fragment key={index}>
<button
className='dropdown-btn bg-transparent haschild'
style={{ border: 'none' }}
>
{data.name} <i className='fas fa-chevron-right'></i>
</button>
<div
className='dropdown-container'>
<Content
config={menuItem.children}
children={true}
/>
</div>
</Fragment>
and on use effect
useEffect(() => {
var dropdown = document.getElementsByClassName("haschild");
var i;
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", function () {
this.classList.toggle("active");
var dropdownContent = this.nextElementSibling;
if (dropdownContent.style.display == "none") {
dropdownContent.style.display = "block";
} else {
dropdownContent.style.display = "none";
}
});
}
},[]);
wherever i have class has child
on that element i have to toggle a class active
and on its next siblings , want to add style attr with display
When using a Framework like react that doesn't directly manipulate the DOM it's not recommended to change style like that.
What you should do instead is to either work with classes and toggle them in react, not using document.getElementsByClassName or similar functions.
This could look something like this, depending on your need:
const ToggleButton = () => {
const [active, setActive] = useState(false);
return (
<button onClick={() => setActive(prev => !prev)} className={active ? 'active' : 'inactive'}>
Toggle active
</button>
);
};
This component would render a button that can be clicked to toggle between the classes active and inactive. The rest can and perhaps should be done with purely CSS.
Modern CSS combinators like ~ can be used to affect following elements. You can read more about CSS combinators here