Change a Component Class React to a hook useState React-Native

Asked

Viewed 155 times

0

I want to transform this code of class in a code of useState hook, wanted the same functionality as this code class has become the Hook

export default class App extends Component { constructor(props) {
  super(props); this.state = {
      selectedStartDate: null, selectedEndDate: null,
  };

  this.onDateChange = this.onDateChange.bind(this);
  }


  onDateChange(date, type){
     if (type === 'END_DATE') {
  this.setState({ 
    selectedEndDate: date,
  });

  } else { this.setState({

    selectedStartDate: date, 
    selectedEndDate: null,
  });
 }
}


render() {

   const { selectedStartDate, selectedEndDate } = this.state;  
   const startDate  =  selectedStartDate ? selectedStartDate.toString() : '';
   const endDate = selectedEndDate ? selectedEndDate.toString() : '';
   return (
     <View style={styles.container}>      
     <CalendarPicker 
        startFromMonday={true} 
        allowRangeSelection={true} 
        selectedDayColor="#BA55D3"
        selectedDayTextColor="#000000"     
        selectedDayStyle="#FFF000"
        todayBackgroundColor="#f22465" 
        selectedDayColor="#8df252" 
        selectedDayTextColor="#0f0f0f" 
        onDateChange={this.onDateChange}
     />

1 answer

0

import React, { useState } from 'react';

export default function App (props) {
  this.state = {
      selectedStartDate: null, selectedEndDate: null,
  };
  
  const [selectedStartDate, setSelectedStartDate] = useState(null);
  const [selectedEndDate, setSelectedEndDate] = useState(null);


  function onDateChange(date, type){
     if (type === 'END_DATE') {
        setSelectedEndDate(date);
     } else {
        setSelectedStartDate(date)
        setSelectedEndDate(null)
     }
  }


  return (
    <View style={styles.container}>      
    <CalendarPicker 
      startFromMonday={true} 
      allowRangeSelection={true} 
      selectedDayColor="#BA55D3"
      selectedDayTextColor="#000000"     
      selectedDayStyle="#FFF000"
      todayBackgroundColor="#f22465" 
      selectedDayColor="#8df252" 
      selectedDayTextColor="#0f0f0f" 
      onDateChange={onDateChange}
    />
  )
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.