giliev
giliev

Reputation: 3058

How to render one React Native component after another component had rendered?

Let's say I have 2 components A and B. I want to render component A and after that render component B. To make that more obvious, I would also like to set some delay (let's say 2 seconds) between the rendering of A and B. What would be the best way to approach this? I guess I should somehow trigger the rendering of B in the componentDidMount of A, but I don't really know how to do that triggering.

Thanks :)

Upvotes: 2

Views: 5831

Answers (2)

user926721
user926721

Reputation:

Your question is very vague and open to multiple implementation. Here's my take:

export default class App extends Component {
  constructor() {
    super()
    this.state = { displayComponentB: false }
    this.displayComponentB = this.displayComponentB.bind(this)
  }
  displayComponentB() {
    setTimeout(() => {
      this.setState({ displayComponentB: true })
    }, 2000) // delay
  }
  render() {
    return (
      <View style={styles.container}>
        <ComponentA onComponentDidMount={this.displayComponentB}/>
        {
          this.state.displayComponentB && 
          <ComponentB />
        }
      </View>
    );
  }
}

export class ComponentA extends Component {
  componentDidMount() {
    this.props.onComponentDidMount && this.props.onComponentDidMount()
  }
  render() {
    return (
      <View style={[styles.component, styles.componentA]}>
        <Text style={styles.text}>Component A</Text>
      </View>
    );
  }
}

Full code and live demo: https://snack.expo.io/SkIOLJ3eM

Upvotes: 2

yangguang1029
yangguang1029

Reputation: 1823

use setTimeout in componentDidMount.

here is a sample

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

componentDidMount(){
    setTimeout(() => {
        this.setState({isBVisible:true});
    }, 2000);
}

render(){
    return(<View>
        <View style={{width:100,height:100,backgroundColor:"red"}}/>
        {this.state.isBVisible ? <View style={{width:100,height:100,backgroundColor:"green"}}/>:null}
    </View>)
}

Upvotes: 2

Related Questions