Home > Mobile >  fuctional compoent into class compoent react js
fuctional compoent into class compoent react js

Time:10-06

i been trying to covert a fuctional compoent into class compoent but i get error

functional componet

export default function App() {
  const [dateState, setDateState] = useState(new Date())
  const changeDate = (e) => {
    setDateState(e)
  }
let clikededate = moment(dateState).format('MMMM Do YYYY')}
  return (
    <>
      <Calendar 
      value={dateState}
      onChange={changeDate}
      />
  
   <>


class compoenet

constructor(props) {
    super(props);
   
    this.state = {
    
      dateState: new Date(),
    };

 changeDate(e) {
   
    this.setState({ dateState: e });
  
  
  }
 let clikededate = moment(this.state.dateState).format('MMMM Do YYYY')
render() {
 }

  return (
    <>
     <Calendar
       onChange={this.changeDate}
       value={this.dateState}
    />
   <>
  )
}

i been trying to covert a fuctional compoent into class compoent but i get error

CodePudding user response:

Im not sure if its the only error but you have to add render() method wrapping the return in the class component.

CodePudding user response:

Return should be inside a render function. also any local variables should be inside the function it is being used. Try the following code;

constructor(props) {
    super(props);
   
    this.state = {
    
      dateState: new Date(),
    };

 changeDate(e) {
   
    this.setState({ dateState: e });
    // this.setState({ dateState: e.target.value }); // maybe this?
  
  }

render() {
  let clikededate = moment(this.state.dateState).format('MMMM Do YYYY')}

  return (
    <>
     <Calendar
       onChange={this.changeDate}
       value={this.dateState}
    />
   <>
  )
}
  

CodePudding user response:

I see some issue

1- You close constructor after changeDate and render method, It's WORNG

2- e.target.value

3- bind changeDate

4- Close fragment

class **** extends React.Component {

constructor(props) {
  super(props);
 
  this.state = {
    dateState: new Date(),
  };
    this.changeDate= this.changeDate.bind(this);

}// close constructor

  changeDate(e) {
    this.setState({ dateState: e.target.value });// e.target.value 
  }

  let clikededate = moment(this.state.dateState).format('MMMM Do YYYY')
render() {
return (
  <>
   <Calendar
     onChange={this.changeDate}
     value={this.dateState}
  />
 </>//close your fragment
)
}
}
  • Related