pratteek shaurya
pratteek shaurya

Reputation: 960

Determine if a date is saturday or sunday using react

Can we determine if a date is saturday or sunday using react. If so, then how will it be implemented?

I have a table:

import React, { Component } from "react";
class HomePage extends Component {
    render() {
        return (
            <div className="main">
                <table>
                    <tr>
                        <th colSpan="7">Nov</th>
                    </tr>
                    <tr>
                        <th colSpan="7">Week 1</th>
                    </tr>
                    <tr>
                        <td>16</td><td>17</td><td>18</td><td>19</td><td>20</td><td>21</td><td>22</td>
                    </tr>
                </table>
            </div>
        )
    }
}
export default HomePage;

I want to highlight the date which is saturday or sunday. I am very new to react and I cant figure out how to do this.

Upvotes: 0

Views: 818

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

This is not react specific. Construct a Date from the number and get it's week day

function isWorkDay(date, month = 10, year = 2020) {
  const weekDay = new Date(year, month, date).getDay()
  return  weekDay !== 0 && weekDay !== 6; 
}

function isWorkDay(date, month = 10, year = 2020) {
  const weekDay = new Date(year, month, date).getDay()
  return  weekDay !== 0 && weekDay !== 6; 
}

function DateCell({date}) {
  return <td className={isWorkDay(date) ? 'workday' : 'weekend'}>{date}</td>
}

class HomePage extends React.Component {
    render() {
        return (
            <div className="main">
                <table>
                <tbody>
                    <tr>
                        <th colSpan="7">Nov</th>
                    </tr>
                    <tr>
                        <th colSpan="7">Week 1</th>
                    </tr>
                    <tr>
                        {
                          [16, 17, 18, 19, 20, 21, 22].map(date => <DateCell key={date} date={date} />)
                        }
                    </tr>
                 </tbody>
                </table>
            </div>
        )
    }
}

ReactDOM.render(<HomePage />, document.querySelector('#app'))
.weekend {
  background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.development.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.development.min.js"></script>
<div id="app" />

Upvotes: 1

Related Questions