score:4
one way to do this is to use array map with index like this:
import react, { usestate } from "react";
export default function app() {
const days = ['monday', 'tuesday', ... ]
const [activeindex, setactiveindex] = usestate(-1);
const handletoggle = (index) => {
setactiveindex(index);
};
return (
<div >
{days.map((day, index) => (
<button onclick={()=> handletoggle(index)} classname={activeindex === index ? "active" : null}>{day}</button>
)
</div>
);
}
score:1
you can extract your button-props to a function if the markup gets a bit longwinded
export default function app() {
const [chosen, choose] = react.usestate();
const makeprops = (name) => ({
onclick: () => choose(name),
classname: chosen === name ? 'active' : null
})
return (
<div classname="app">
<button {...makeprops('one')}>one</button>
<button {...makeprops('two')}>two</button>
<button {...makeprops('duck')}>duck</button>
</div>
);
}
or encapsulate the entire behaviour to its own 'buttonthatcanbeactive' component that takes a "active" and "onclick" prop
score:4
assuming you have a src/index.css
file that contains the required css class... your current script will assign the "active" class to all buttons at once. to apply the class to a single button you need to have an object in state like so:
const [daysactive, setdaysactive] = usestate({ monday: false, tuesday: false... });
and in your toggle method you will pass the day key as such:
const handletoggle = (day) => {
setdaysactive({
...daysactive,
[day]: !daysactive[day]
});
}
so a jsx button will call this handler with its respective day key
<button onclick={() => handletoggle("sunday")} classname={daysactive["sunday"] ? "active" : null}>sunday</button>
if you'd like to make this button set cleaner you can use the map function
const days = ["sunday", "monday", ...];
<div>
{days.map((day) => (
<button ... />
))}
</div>
Source: stackoverflow.com
Related Query
- How to add a tab dynamically when we click a button using React js and Bootsrap 4
- In React, how to add class to button when click
- How to scroll to newly added row in a table automatically when we click on add row button in React JS
- how to add a tab dynamically when we click a particular button using react js?
- How do I add a transition to my navbar menu in react when I click the toggle button
- How to add a CSS class to an element on click - React
- How to make one table record editable on button click in React when the table record is mapped?
- how to add input field dynamically when user click on button in react.js
- How to remove active class when click another toggle button in React.js?
- how to change background color when I click the button using react hooks
- React Js how to jump whole pages to other pages when click on the navigation button
- How to restrict formik validation when you click cancel button in react
- On button click, how to add selected class and remove from all other buttons in React functional component?
- How to add a <Field /> when a button is clicked inside a Form with React & Formik?
- React using reactstrap navbar: how to add and remove class on navbar tag when window scrolls
- How can strike a post out when i click the complete button in React
- How to show a component When I click a button using function components in react
- How can I add a class to a button when a Formik Form isSubmitting?
- How do I target and change the style of a different element when I click a button in react
- How to add a new textfield on button click and add integer value of that input field to an array in react
- I want the image to change when i click the button in class component React JS
- React how to add class to parent element when child element is clicked
- how to add code more in react to hide and show pages when I click again
- How to hide a button when I click the button in react using functional components
- react how to make call modal when button click event
- react - how to show relevant element when click button
- how to handle focus same item when hardware back button click in react native for android Tv app
- How to add styles to individual elements in react using e.target, when a button is clicked?
- How do I add a class to a react element when it is clicked
- how do i toggle the div when click outside of the button in react js?
More Query from same tag
- used an API. import and in components>DrinkList.js handleTextShow function not running
- How to update React localhost (127.0.0.1:3000) to another domain (local.example.com)
- when does useEffect fire in componentWillUnmount?
- UnhandledScheme & cannot read properties of undefined errors using React.JS
- Iterating through object in React
- Changing the default main file "index.js" to some other file in react?
- How to remove file from react-dropzone?
- How bad is it to change the DOM in react?
- Designing / combining redux reducers
- How can I make sure conditional rendering in event handlers in tables in React?
- How to call parent function from child prop without an arg
- Trying to create a controlled switcher button
- React Dropbox Component using Material-UI-Next
- Child to parent communication in React (JSX) without flux
- How to pass a value from React Context into a Redux-Saga function?
- React require("history").createBrowserHistory` instead of `require("history/createBrowserHistory")
- Cannot read property 'refs' of null react error react js
- React recursively call method on children
- How to extend class name with condition in React?
- Load assets accompanying a Javascript from a remote location
- ReactJS: Control a child state from the child and the parent
- react TypeError: Cannot read property 'fulfilled' of undefined on Redux tool kit
- draft.js: text editor populate value from other component's state
- Formik & Yup | Multiple files upload validation
- Show div when there's not data available in getServerSideProps with NextJS?
- How do you encode a file to base64 then upload as multipart file to backend api using JS?
- How to refactor the if else code using typescript and react?
- npm ci passing locally but failed on gitlab
- Webpack: How to use prebuilt version of react and other libraries
- Material-UI Drawer with Flexbox horizontal scroll not working on iOS Safari