Answer the question
In order to leave comments, you need to log in
How to reset the state of all components with one button?
How to write logic correctly so that the reset button makes all texts black again?
When I click on the text, it changes to red, I click again and it changes to black.
And when I press reset, nothing happens.
import './App.css';
import Text from './Text/Text';
import {useState} from 'react'
function App() {
let [status, setStatus] = useState(false)
let list = [
{id: 1, text: 'Text 1'},
{id: 3, text: 'Text 2'},
{id: 2, text: 'Text 3'},
]
function resetColor(params) {
setStatus(false)
}
return (
<div className="App">
<button
onClick={()=>{resetColor()}}
>reset color</button>
{list.map(({id, text}) => {
return (
<Text key={id} text={text} />
)
})}
</div>
);
}
export default App;
import React from 'react';
import './text.css';
import { useState } from 'react'
const Text = ({text, status}) => {
let [active, setActive] = useState(status);
function changeColor() {
console.log('work');
setActive(active = !active)
}
return (
<p
className={active ? 'red-text' : ''}
onClick={()=>{changeColor()}}
>
{text}
</p>
);
};
export default Text
Answer the question
In order to leave comments, you need to log in
You don’t have reverse logic; it only puts you in the false position on click and
write everything in the function like this:
const resetColor = () => {
status ? setStatus(false) : setStatus(true);
Store the values responsible for the color of the text in the parent component, along with the rest of the data:
const [ items, setItems ] = useState([
{ id: ..., text: '...', active: false },
{ id: ..., text: '...', active: false },
...
]);
const reset = () => setItems(items.map(n => ({ ...n, active: false })));
<button onClick={reset}>reset</button>
const toggle = id => setItems(items.map(n => n.id === id ? { ...n, active: !n.active } : n));
{items.map(n => <Text key={n.id} {...n} toggle={toggle} />)}
const Text = ({ id, text, active, toggle }) => (
<p
className={active ? 'active' : ''}
onClick={() => toggle(id)}
>
{text}
</p>
);
function resetColor(params) {
setStatus(prevStatus => !prevStatus)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question