0

I'm trying to convert react function to react class

  const prevSplash = () => {
         if (index === 1) {
             setIndex(0);
         } else {
             setIndex(prev => prev - 1);
         }
     }

    const [index, setIndex] = React.useState(0);
    React.useEffect(() => {
        const timer = setInterval(() => {
            if (index === 1) {
                setIndex(0);
            } else {
                setIndex(prev => prev + 1);
            }
        }, 10000);
        return () => clearInterval(timer);
    },); 
0

1 Answer 1

1

Try to defined useState property in this.state in class and your useEffect function in componentDidMount.

Your code will be like:

import React,{Component} from 'react';
class Demo extends Component{
   constructor(props){
     super(props);
     this.state = {
         index:0
     }
   }

   prevSplash = () => {
      if (this.state.index === 1) {
       this.setState({...this.state,index:0});
      } else {
          this.setState((prev)=>({
                  index:prev.index-1
          }));
        }
   }

   componentDidMount(){
     const timer = setInterval(() => {
       if (this.state.index === 1) {
           this.setState({...this.state,index:0});
       } else {
          this.setState((prev)=>({
          index:prev.index+1
        }));
     }
    }, 10000);

   return () => clearInterval(timer);

   }; 

   render() {
    return (
             <h1>
                //your code 
             </h1>
          )
     }
   }
}

export default Demo;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.