Lion
Lion

Reputation: 7

Class To Function Component

I am very new to react native. The app I am developing has functional components.

Is there any way to convert class component to function component or convert this class into a function?

Is it possible to use functional and class component both in single app?

import React from 'react';
import DayPicker, { DateUtils } from 'react-day-picker';
import 'react-day-picker/lib/style.css';

export default class Example extends React.Component {
  constructor(props) {
    super(props);
    this.handleDayClick = this.handleDayClick.bind(this);
    this.state = {
      selectedDays: [],
    };
  }

  handleDayClick(day, { selected }) {
    const { selectedDays } = this.state;
    if (selected) {
      const selectedIndex = selectedDays.findIndex(selectedDay =>
        DateUtils.isSameDay(selectedDay, day)
      );
      selectedDays.splice(selectedIndex, 1);
    } else {
      selectedDays.push(day);
    }
    this.setState({ selectedDays });
  }

  render() {
    return (
      <div>
        <DayPicker
          selectedDays={this.state.selectedDays}
          onDayClick={this.handleDayClick}
        />
      </div>
    );
  }
}

Upvotes: 0

Views: 104

Answers (1)

AlainIb
AlainIb

Reputation: 4708

Yes you can use both functional and class component in same time

    import React, {useState} from "react";
    import DayPicker, { DateUtils } from 'react-day-picker';
    import 'react-day-picker/lib/style.css';

    export default function Example(props = {}) { 

       // read about useState hooks, it replace state 
      const [selectedDays, setSelectedDays] = useState([]);


      handleDayClick(day, { selected }) {

        if (selected) {
          const selectedIndex = selectedDays.findIndex(selectedDay =>
            DateUtils.isSameDay(selectedDay, day)
          );
          selectedDays.splice(selectedIndex, 1);
        } else {
          selectedDays.push(day);
        }
        setSelectedDays( selectedDays );
      }

      render() {
        return (
          <div>
            <DayPicker
              selectedDays={ selectedDays}
              onDayClick={handleDayClick}
            />
          </div>
        );
      }
    }

Upvotes: 1

Related Questions