I have 3 button like this, I want set default color when component render first time. Any idea?
<Button onClick={setChartDay}>Day</Button>
<Button onClick={setChartWeekly}>Week</Button>
<Button onClick={setChartMonth}>Month</Button>
My css
'& button:active': {
color: styles.color.white,
backgroundColor: styles.color.darkBlue,
},
'& button:focus': {
color: styles.color.white,
backgroundColor: styles.color.darkBlue,
},
CodePudding user response:
You can use a default state in useState
for the first rendering. In your case, it would be Day
.
const BUTTONS = {
Day: "Day",
Week: "Week",
Month: "Month"
}
const App = () => {
const [activeButton, setActiveButton] = React.useState(BUTTONS.Day)
const setChartDay = () => {
setActiveButton(BUTTONS.Day)
//TODO: Logic for day chart
}
const setChartWeekly = () => {
setActiveButton(BUTTONS.Week)
//TODO: Logic for week chart
}
const setChartMonth = () => {
setActiveButton(BUTTONS.Month)
//TODO: Logic for month chart
}
return <div>
<button onClick={setChartDay} className={activeButton === BUTTONS.Day && "active"}>Day</button>
<button onClick={setChartWeekly} className={activeButton === BUTTONS.Week && "active"}>Week</button>
<button onClick={setChartMonth} className={activeButton === BUTTONS.Month && "active"}>Month</button>
</div>
}
ReactDOM.render(
<App/>,
document.getElementById("root")
);
button.active {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>