简体   繁体   中英

Styling different values of an array in React.js

I have an array that is getting data from an API, but I want to style each button differently so that the background colours differ. I am also using Material UI... Here is my code -

{options.map((data, id) => (
 <Button className='p-3 md:w-[25wh] md:h-[25vh]' onClick={handleClickAnswer} fullWidth variant="contained">{decode(data)}</Button>
))}

Please tell me how to style them

There are several ways in which you can assign different styles to different buttons. It can be done majorly using string literals.

Few examples,

  1. If you are using bootstrap/tailwind and your styling will majorly consist of that, then you can something like

 {options.map((data, id) => ( <Button className=`p-${id} md:w-[25wh] md:h-[25vh]` onClick={handleClickAnswer} fullWidth variant="contained"> {decode(data)} </Button> ))}

Notice p-${id} would get modified for each particular element in the array

  1. Even if bootstrap isn't being used, you can use the above method, create custom classNames to assign styles to each button separately.
  2. If you need to specifically assign a style to the first/last element, you can use first child selector (or) last child selector .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM