obiwankenoobi
obiwankenoobi

Reputation: 1582

render component inside setTimeout method not working

I am trying to render component in some delay and I want to use setTimeout() (not that it must be using that method but I dont know other ways) and I don't know why , I must do it wrong but it's just wont render the component

CODE:

      <View>
        <Image 
          source={require('./assets/img/1.gif')} 
        />
          {
            setTimeout(() => {
              return (
                <Text>some text</Text>
              )
            }, 5000)
          }            
      </View>   

Upvotes: 1

Views: 5170

Answers (4)

nerdess
nerdess

Reputation: 10920

The above answer needs some improvements, otherwise the useEffect would not be cleaned up properly

const YourComponent = () => {

    const [state, setState] = useState(false);

    useEffect(() => {
        const timeout = setTimeout(()=>setState(true), 5000)
        return () => {
            clearTimeout(timeout);
            setState(false);
        }
    }, []);

    if (state) {
        return <>5 Seconds have passed</>;
    }

    return null;
};

Upvotes: 0

Jessa Daggs
Jessa Daggs

Reputation: 1

Here's a solution using useEffect.

  // import useEffect and useState
  import React, { useEffect, useState } from 'react';
  ... your other code 
  // setTimeout is a side effect and must exist inside of a useEffect hook. Use it to update state. Then conditionally render your component.
  const YourComponent = () => {

    const [state, setState] = useState(false);

    useEffect(() => setTimeout(()=>setState(true), 5000), []);

    return (
      <div>
        <View>
          <Image 
            source={require('./assets/img/1.gif')} 
          />
            {state === true ? <Text>some text</Text> : null}            
        </View>  
      </div>
    )
  }

Upvotes: 0

obiwankenoobi
obiwankenoobi

Reputation: 1582

Ok I fixed it by creating flag in the state , set it to false and created handler to set it to true with setTimeout() and attached it to other function that invoked earlier.

CODE:

  state = {
   animationFlag: false
  }

  flagHandler = () => {
    setTimeout(() => {
      this.setState({
        animationFlag: true
      })
    }, 4000)
  }

    <View>
     <Image source={require('./assets/img/1.gif')}/>
       {
       this.state.animationFlag ? <Text>some text</Text> : null
       }            
   </View>

Upvotes: 0

mokk
mokk

Reputation: 916

You could try something like that:

constructor(props) {
 super(props)
 this.state = {
  showText: false
 }
}

componentDidMount() {
 setTimeout(() => {
   this.setState({ showText: true })
 }, 5000)
}

render() {
 const { showText } = this.state

 return (
  <div>
   <Image source={require('./assets/img/1.gif')} />
   {showText && <Text>some text</Text>}
  </div>
 )
}

Upvotes: 4

Related Questions