Changing classname of a specific element on click from a mapped array an keeping the same classname until clicked again in react
You need to be able to keep track of every index that's checked - for this you'll need an array (or a number you do bit calculations with). A stateful index
number doesn't contain enough information.
const allTodos = [{ id: 1, name: 'whatever user type' }, { id: 2, name: 'foo' }];
const Todos = ({ allTodos }) => {
const [todos, setTodos] = React.useState(() => allTodos.map(todo => ({ ...todo, checked: false })));
const handleClick = (i) => () => {
setTodos(todos.map((todo, j) => j !== i ? todo : ({ ...todo, checked: !todo.checked })))
};
return todos.map(({ id, name, checked }, i) => (
<div id="item_container">
<button
type='button'
className={`check_button ${checked ? 'checked' : 'not_checked'}`}
onClick={handleClick(i)}
>
<img alt="Sample Image" id="check_img"></img>
</button>
<div>{name}</div>
</div >
))
}
ReactDOM.render(<Todos allTodos={allTodos} />, document.querySelector('.react'));
.checked {
background-color: green;
}
.not_checked {
background-color: yellow;
}
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
Modify className when element is clicked in React
To make it work using your way, you will have to store isActive
key for each menu object. Your addClass()
function should be like this:
addClass = e => {
this.setState({
menus: this.state.menus.map(menu => ({
...menu,
isActive: e.target.id == menu.id
}))
})
}
Each time addClass is called, we go through each menu object, if the menu's id match the ID user has clicked, we give it isActive: true
, else we set it to false. And of course we use .map
to return a new set of menus since we can't mutate this.state.menus
directly.
Then we can check whether a menu is active or not by checking its isActive
key:
{
this.state.menus.map(menu =>
<a
className={`nav ${menu.isActive ? 'active' : ''}`}
id={menu.id}
onClick={this.addClass}
>
{menu.menu}
</a>
)
}
Built this working snippet for you:
class Hello extends React.Component { state = { menus: [{id:0,menu:"Home"}, {id:1,menu:"Contact"}, {id:2,menu:"About"}] }
addClass = e => { this.setState({ menus: this.state.menus.map(menu => ({ ...menu, isActive: e.target.id == menu.id })) }) }
render() { return ( <div> { this.state.menus.map(menu => <a style={{color: menu.isActive ? 'red' : 'black'}} className={`nav ${menu.isActive ? 'active' : ''}`} id={menu.id} onClick={this.addClass} > {menu.menu} </a> ) } </div> ) }}
ReactDOM.render( <Hello name="World" />, document.getElementById('container'));
<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="container"></div>
Change Class Name in React state
Since inputAll
is a List of Objects, meaning there is no key for a list item but there is an index, you should know the id
field or any other identifier and search for that object in the list in order for you to be able update the class name.
const changeClass = (id) => {
inputAll.forEach((item) => {
if(item.id === id){
item.className = newClass;
}
}
setInputAll([...inputAll])
}
OR
const changeClass = (index) => {
inputAll[index].className = newClass;
setInputAll([...inputAll]);
}
In React, how do I change the classname of one element that was created in an iteration, onclick of another element?
Put the status of whether a row is disabled or not into the data.list
array in state. Probably something like:
{data.list.map((item, i) => (
// ...
onClick={(e) => handleRemove(i)
const handleRemove = (index) => {
setData({
...data,
list: [
...data.list.slice(0, index),
{ ...data.list[index], disabled: true },
...data.list.slice(index + 1),
]
});
};
Then, when rendering, use the disabled
property to give the row a class name.
<div
className={`c-table__row${item.disabled ? ' disabled' : ''}`}
key={item.id}
>
How to add or remove a className on event in ReactJS?
The list of classes can be derive from the state of the component. For example:
var Component = React.createClass({
getInitialState: function() {
return {
clicked: false
};
},
handleClick: function() {
this.setState({clicked: true});
},
render: function() {
var className = this.state.clicked ? 'click-state' : 'base-state';
return <div className={className} onClick={this.handleClick}>click here</div>;
}
});
Calling this.setState
will trigger a rerender of the component.
How can I change the class of an element dynamically via url in React?
You can do something like that:
function CustomLink({ children, to, ...props }: LinkProps) {
let resolved = useResolvedPath(to);
let match = useMatch({ path: resolved.pathname, end: true });
return (
<div>
<Link
style={{ textDecoration: match ? "underline" : "none" }}
to={to}
{...props}
>
{children}
</Link>
{match && " (active)"}
</div>
);
}
Related Topics
Onchange Is Not Triggering in React Js
Extracting Key:Value Pairs Assoc With Regex from String on JavaScript
Javascript Date Validation ( Dd/Mm/Yyyy) & Age Checking
Verify External Script Is Loaded
Set Some Specific Options in Multiselect as Disabled and Selected
Javascript Odd and Even Separation in an Array of Numbers
Using Js Remove Comma from Number from Existing Data
Vuetify: How to Preselect Active Tab
Detect Click into Iframe Using JavaScript
Google Firestore - How to Get Several Documents by Multiple Ids in One Round-Trip
How to Check If Character Is a Letter in JavaScript
How to Allow Chrome to Access My Camera on Localhost
How to Export or Convert Json to Excel in Angularjs
How to Check Whether Dynamically Attached Event Listener Exists or Not
How to Remove Duplicates Elements Between 2 Arrays in Angular