Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div id="root"></div>
              
            
!

CSS

              
                
              
            
!

JS

              
                const { Component } = React;
const { css, createGlobalStyle } = styled;


const GlobalStyles = createGlobalStyle`
  * { box-sizing: border-box; }

  html, body {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
    background-color: #f4f4f4;
    color: #2a2a2a;
  }
`;

const Container = styled.div`
  max-width: 720px;
  margin: 1rem auto;
  text-align: center;
`;

class App extends Component {
  render() {
    return (
      <>
        <GlobalStyles />
        <Container>
          <Calendar />
        </Container>
      </>
    );
  }
}

/**
 * CALENDAR
 */

function formatDate(date, locale = 'de') {
    const yyyy = date.getFullYear();
    const m = date.getMonth() + 1;
    const mm = m < 10 ? '0' + m : m;
    const d = date.getDate();
    const dd = d < 10 ? '0' + d : d;

    switch (locale) {
        case 'de': return `${dd}.${mm}.${yyyy}`;   
        case 'us': return `${yyyy}-${mm}-${dd}`;   
        default: return date;
    }
  }

function dateFromString(date, locale = 'us') {
  switch (locale) {
    case 'de': {
      const parts = date.split('.');
      return new Date(parts[2], parts[1] - 1, parts[0]);
    }
    case 'us': {
      const parts = date.split('-');
      return new Date(parts[0], parts[1] - 1, parts[2]);
    }
    default:
      return new Date(date);
  }
}

function datesEqual(date1, date2) {
  const date1WithoutTime = new Date(date1.setHours(0,0,0,0));
  const date2WithoutTime = new Date(date2.setHours(0,0,0,0));
  return date1WithoutTime.getTime() === date2WithoutTime.getTime();
}

const CalendarWrapper = styled.div`
  display: inline-block;
  margin: 1rem 0;
  padding: 1rem;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  user-select: none;
  text-align: left;
`;

const Controls = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1rem 0;
`;

const Button = styled.button`
  background-color: transparent;
  padding: 0.5rem 0.75rem;
  border: 1px solid #ddd;
  border-radius: 0.25rem;
  outline: 0;
  cursor: pointer;
  &:hover {
    background-color: #ddd;
  }
`;

const Input = styled.input`
  font-size: 1rem;
  padding: 0.5rem 0.75rem;
  border: 1px solid #ddd;
  border-radius: 0.25rem;
  outline: 0;
  margin: 0 0.5rem;
`;

const SelectedDate = styled.div`
  margin: 0 0.75rem;
`;

const SelectTodayButton = styled(Button)`
  margin-left: auto;
  color: #fff;
  background-color: rgba(204, 34, 34, 0.75);
  &:hover {
    background-color: rgba(204, 34, 34, 1);
  }
`;

const Days = styled.div`
  width: 100%;
  display: inline-grid;
  grid-template-columns: repeat(7, 1fr);
  margin-top: 1rem;
`;

const Weekday = styled.div`
  height: 2rem;
  background-color: rgba(0, 0, 0, 0.15);
  opacity: 0.75;
  display: flex;
  justify-content: center;
  align-items: center;

  ${p => p.weekend && `color: rgba(0,0,0, 0.35);`}
`;


const Day = styled.div`
  position: relative;
  width: 2.5rem;
  height: 2.5rem;
  margin: 0.25rem;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 0.25rem;
  cursor: pointer;

  border: 1px solid ${p =>
    (p.today && '#c22') || 
    (p.selected && '#ccc') || 
    'transparent'
  };

  ${p => p.columnStart && `grid-column-start: ${p.columnStart};`}

  ${p => p.weekend && `color: rgba(0,0,0, 0.35);`}
  
  &:hover {
    background-color: rgba(0, 0, 0, 0.05);
  }

  ${p => p.hasTermine && css`
      &:after {
        content: '';
        display: block;
        position: absolute;
        top: 4px;
        left: 4px;
        width: 0.35rem;
        height: 0.35rem;
        background-color: ${p.hasUnfinishedTermine ? 'coral' : 'grey'};
        border-radius: 50%;
      }
    `};
`;

const Termine = styled.div`
  padding: 1rem;
`;

const Termin = styled.div`
  margin: 0.5rem 0;
  &:first-child { margin-top: 0; }  
  &:last-child { margin-bottom: 0; }

  input {
    margin-right: 0.5rem;
  }
`;

const AddDateForm = styled.form`
  border-top: 1px solid rgba(0,0,0, 0.1);
  padding-top: 1rem;
  margin-top: 1rem;
`;


class Calendar extends Component {
  state = {
    today: new Date(),
    date: null,
    newTerminDate: null,
    termine: []
  };

  // set default state values
  componentWillMount() {
    const defaultTermine = [
      { id: 1, date: '2018-04-03', title: 'Seminar', finished: true},
      { id: 2, date: '2018-04-03', title: 'Workshop', finished: false},
      { id: 3, date: '2018-04-21', title: 'Meeting', finished: false},
      { id: 4, date: '2018-05-04', title: 'Seminar', finished: false}
    ];
    const termine = defaultTermine;
    
    this.setState(state => ({
      date: new Date(state.today.getTime()),
      newTerminDate: new Date(state.today.getTime()),
      termine
    }));
  }

  componentDidUpdate(prevProps, prevState) {
    // set this.state.newTerminDate to this.state.date
    if (prevState.date !== this.state.date) {
      this.setState({
        newTerminDate: this.state.date
      });
    }
  }

  weekdays = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];
  

  /**
   * SETTER
   */

  previousMonth = () => {
    this.setState(state => ({
      date: new Date(state.date.setMonth(state.date.getMonth() - 1))
    }));
  }

  nextMonth = () => {
    this.setState(state => ({
      date: new Date(state.date.setMonth(state.date.getMonth() + 1))
    }));
  }

  selectToday = () => {
    this.setState(state => ({
      date: new Date(state.today.getTime())
    }));
  }

  selectDate = (date) => {
    this.setState(state => ({
      date: new Date(state.date.setDate(date))
    }));
  }
  
   toggleTermin = id => {
    this.setState(state => ({
      termine: state.termine.map(termin =>
        termin.id === id
          ? {...termin, finished: !termin.finished}
          : termin
      )
    }))
  }
   
  addDate = (e) => {
    e.preventDefault();
    const title = this.newTerminTitle.value;
    const date = this.newTerminDate.value;
    if (date && title && date.length > 1 && title.length > 1) {
      const termin = {
        date,
        title,
        finished: false,
        id: this.state.termine.length
          ? this.state.termine[this.state.termine.length -1].id + 1
          : 0
      };  
      this.setState(state => ({
        termine: [...state.termine, termin]
      }), () => {
        this.newTerminForm.reset();
      });
    }    
  }
  
  
  /**
   * GETTER
   */
   
  termineForDate = date =>
    this.state.termine.filter(
      termin => datesEqual(dateFromString(termin.date), date)
    );
  

  /**
   * RENDERER
   */

  renderWeekdays = () => this.weekdays.map((weekday, i) => (
    <Weekday key={i} weekend={i === 5 || i === 6}>{weekday}</Weekday>
  ))

  renderDays = () => {
    const date = this.state.date;
    const currentYear = date.getFullYear();
    const currentMonth = date.getMonth();
    const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();

    const days = [];
    for (let day = 1; day <= daysInMonth; day++) {
      const currentDate = new Date(currentYear, currentMonth, day);
      days.push(
        <Day
          key={day}
          data-date={formatDate(currentDate)}
          onClick={() => this.selectDate(day)}
          columnStart={day === 1 && (currentDate.getDay() || 7)}
          selected={day === this.state.date.getDate()}
          today={datesEqual(currentDate, this.state.today)}
          hasTermine={this.termineForDate(currentDate).length}
          hasUnfinishedTermine={this.termineForDate(currentDate).filter(termin =>
            !termin.finished).length
          }
          weekend={currentDate.getDay() === 0 || currentDate.getDay() === 6}
          title={
            this.termineForDate(currentDate).length
              ? 'Termine:\n' +
                this.termineForDate(currentDate).map(termin => '- ' + termin.title).join('\n')
              : ''
          }
        >
          {currentDate.getDate()}
        </Day>
      );
    }
    return days;
  };

  renderTermine = () => {
    const termine = this.termineForDate(this.state.date);
    return termine.length
      ? termine.map(termin => (
        <Termin key={termin.id}>
          <input
            type='checkbox'
            checked={termin.finished}
            id={termin.id}
            onChange={() => this.toggleTermin(termin.id)}
          />
          <label htmlFor={termin.id}>{termin.title}</label>
        </Termin>
      ))
      : 'Keine Termine';
  };

  render() {
    return (
      <CalendarWrapper>
        <Controls>
          <Button onClick={this.previousMonth}>prev</Button>
          <SelectedDate>{formatDate(this.state.date)}</SelectedDate>
          <Button onClick={this.nextMonth}>next</Button>
          <SelectTodayButton onClick={this.selectToday}>
            today
          </SelectTodayButton>
        </Controls>
        <Days>
          {this.renderWeekdays()}
          {this.renderDays()}
        </Days>
        <AddDateForm onSubmit={this.addDate} innerRef={el => this.newTerminForm = el}>
          <Input
            type='date'
            name='date'
            value={formatDate(this.state.newTerminDate, 'us')}
            onChange={e => this.setState({newTerminDate: new Date(e.target.value)})}
            innerRef={el => this.newTerminDate = el}
          />
          <Input
            type='text'
            name='title'
            innerRef={el => this.newTerminTitle = el}
            placeholder='Neuer Termin...'
          />
          {/* <Button type='submit'>add</Button> */}
        </AddDateForm>
        <Termine>{this.renderTermine()}</Termine>
      </CalendarWrapper>
    );
  }
}


ReactDOM.render(<App />, document.getElementById('root'));

              
            
!
999px

Console