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

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 :)

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

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>)
}

Related

Updating changed value on user interface

I want my value to change on the screen when button is pressed. It does change the variable value behind the scenes but has no effect for the outdated value shown on the screen.
export default class App extends Component {
render() {
this.state = {
myVariable: 'egs'
}
const changeValue = () => {
this.state.myVariable = "CHANGED??!!"
}
return (
<View style={styles.container}>
<Text>
{this.state.myVariable}
</Text>
<Button onPress={changeValue} title="CHANGE IT"/>
</View>
);
}
}
I expect to update value to the changed one instead of outdated one.
Move state initialization outside of render as well as the changeValue method
You also cannot mutate statue directly, instead use setState()
This should work:
export default class App extends Component {
state = {
myVariable: 'egs'
}
changeValue = () => {
this.setState({myVariable:"CHANGED??!!"})
}
render() {
return (
<View style={styles.container}>
<Text>
{this.state.myVariable}
</Text>
<Button onPress={changeValue} title="CHANGE IT"/>
</View>
);
}
}
this.state.myVariable = "CHANGED??!!"
change to
this.setState({ myVariable: "CHANGED??!!" })

Pass parameters to prop function without using an arrow function

I've heard that passing an arrow function as a prop is not ideal because it creates a new function every time which will lead to performance issues. However, I'm not entirely sure how to completely move away from them, as can be seen by the example below:
class Home extends Component {
onCardPress = (message) =>{
alert(message)
}
render(){
return(
<View>
<Card
onCardPress={this.onCardPress}
message="Hello world!"
/>
</View>
)
}
}
class Card extends Component {
render(){
const { onCardPress , message } = this.props;
return(
<TouchableOpacity
activeOpacity={0.8}
onPress={()=>{onCardPress(message)}}
/>
)
}
}
I have tried changing onPress in Card to be onPress={onCardPress(message)}, but I know this doesn't work because I am invoking the function rather than passing a function object to the onPress of TouchableOpacity. What is the 'proper' way or best practice to remove the arrow function in TouchableOpacity while still being able to pass the message parameter from the parent component Home?
You could do:
class Card extends Component {
pressHandler = () => this.props.onCardPress(this.props.message);
render() {
return (
<TouchableOpacity
activeOpacity={0.8}
onPress={this.pressHandler.bind(this)}
/>
);
} }
If you want to avoid arrow function, you have to use bind(). Arrow functions will automatically bind "this".
class Home extends Component {
constructor(props) {
super(props);
this.onCardPress = this.onCardPress.bind(this);
}
onCardPress (message) {
alert(message)
}
render(){
return(
<View>
<Card
onCardPress={this.onCardPress}
message="Hello world!"
/>
</View>
)
}
}
class Card extends Component {
render(){
const { onCardPress , message } = this.props;
return(
<TouchableOpacity
activeOpacity={0.8}
onPress={onCardPress(message)}
/>
)
}
}
As I understand it, the issue lies with calling bind inside of render, or returning the handler from yet another lambda, as this will create a new function each time. The conventional way to get around this problem is to bind your handler functions elsewhere -- like in the constructor. In your case, that could look like this:
constructor(props) {
....
this.onCardPress = this.onCardPress.bind(this);
}
...
<Card
onCardPress={this.onCardPress}
message="Hello world!"
/>
Given you alternative option as arrow function already answered in above post.
class Card extends Component {
onClick = () => {
const { onCardPress, message } = this.props;
onCardPress(message);
}
render(){
const { onCardPress , message } = this.props;
return(
<TouchableOpacity
activeOpacity={0.8}
onPress={this.onClick}
/>
)
}
}
You don't need to pass the message prop because you can access it anywhere in the component.
Just supply a function in the onPress prop. And in that function, just access the message prop of the component.
class Home extends Component {
onCardPress = (message) => {
alert(message)
}
render() {
return (
<View>
<Card
onCardPress={this.onCardPress}
message="Hello world!"
/>
</View>
)
}
}
class Card extends Component {
onClick = () => {
const { message, onCardPress } = this.props;
onCardPress(message);
};
render() {
return (
<TouchableOpacity
activeOpacity={0.8}
onPress={this.onClick}
/>
)
}
}

how to get the updated data from parent to child as props

currently, I m trying to pass props data from parent to child and it works fine, but when I m also extracting a field from asyncStorage in the constructor (let's call it brokerName) and then storing it in the props. This is where the issue arrives, the props I m getting in the child element is without brokerName.
This is the parent:
constructor(props) {
super(props);
this.getBrokername();
}
getBrokername = async () => {
const brokerName = await AsyncStorage.getItem('brokerName');
this.props = { brokerName };
console.log('brokerName', brokerName);
}
render () {
return (
<View style={{flex: 1}}>
<View style={{ flex: 1 }}>
<VehicleDetails parentProps={this.props} />
</View>
</View>
);
}
This is the child:
export default class VehicleDetails extends React.Component {
constructor(props) {
super(props);
console.log('vehicleDetails', this.props); // I m not able to get this.props.brokerName
}
}
Any kind of help would be really appreciated.
Thanks.
A few things here.
You should never mutate your props, props are read only, what you want to use in those kinds of situations is state you should read this docs section
Async actions are side effects. At this moment (react 16) you should not have any side effects in the class constructor or render method.
What you're doing doesn't work because your code is async, that means that when the component is created you dispatch a request to fetch some data, but, by the time your component renders that data is not ready to display, another problem originates from my first point, as you're mutating the props instead of using state react doesn't know that it needs to re-render and that's the root of your problem.
To fix this:
Move your async request to componentDidMount lifecycle method check the lifecycle methods here
set state when the request is data is ready
Inject the state as a prop in your child component
Parent
constructor(props) {
super(props);
this.state={
brokerName:null
}
this.getBrokername();
}
getBrokername = async () => {
const brokerName = await AsyncStorage.getItem('brokerName');
this.setState({brokerName:brokerName})
console.log('brokerName', brokerName);
}
render () {
return (
<View style={{flex: 1}}>
<View style={{ flex: 1 }}>
<VehicleDetails brokerName={this.state.brokerName}
/>
</View>
</View>
);
}
Child
export default class VehicleDetails extends React.Component {
constructor(props) {
super(props);
console.log('vehicleDetails', this.props);
}
}
you can get parents props in props key ex : <parent name={name}/> so u can access name using this.props.name
after reading Diogo Cunha's answer, Asif vora's example and Akash Salunkhe's comment above, I came up with this solution and its working fine.
Thanks for all your help.
constructor(props) {
super(props);
this.state={
brokerName:null
}
console.log('details props', this.props);
}
componentDidMount() {
this.getBrokername();
}
getBrokername = async () => {
const brokerName = await AsyncStorage.getItem('brokerName');
this.setState({brokerName:brokerName});
console.log('brokerName', this.state, brokerName);
}
render () {
return (
<View style={{flex: 1}}>
<View style={{ flex: 1 }}>
{this.state.brokerName ? <VehicleDetails parentProps={this.props} brokerName={this.state.brokerName} /> : null }
</View>
</View>
);
}
Please feel free to give your suggestion for any kind of improvement in the answer.

React Native binding functions over .map()

So I am having some trouble combining concepts of .map() and function binding. I am using .map() in the same way ngFor is used in angular, to place a custom button component on the page for every item in a user's account.
Here is some example code:
class MyButton extends Component {
constructor(props) {
super();
this.state = {
progress: 0
}
}
render() {
return(
<TouchableWithoutFeedback onPress={this.pressFunction}>
(...more code inside)
</TouchableWithoutFeedback>
)
}
pressFunction = () => {
(animate progress from 0 to 1 for some animation)
}
}
/////////////////////////////////////////////////////////////////
class Parent extends Component {
render() {
return(
{
this.props.data.array.map(obj => {
return(
<View style={someStyle}>
<MyButton data={obj} />
</View>
)
})
}
)
}
}
So in the Parent Component, multiple MyButtons are rendered properly, each according to the passed object from the array. However, when any button is pressed, all of the pressFunctions for all MyButtons fire.
My question is I guess, how do I ensure that each pressFunction of each MyButton is bound only to the specific instance of the MyButton? I am having trouble with the scope here.
My understanding is that
functionName = () => {}
should properly bind the function to the instance, but I have tried the older ways as well with the same result.
I solved this by creating a dynamic ref on each object mapped to a MyButton, using a unique property of each obj in the array:
this.props.data.array.map(obj => {
return(
<View style={someStyle}>
<MyButton ref={obj.name} data={obj} />
</View>
)
})
Still don't know why my it didn't bind uniquely without a ref
You should pass onPress as a props. Below is the updated code
class MyButton extends Component {
constructor(props) {
super();
this.state = {
progress: 0
}
}
render() {
return(
<TouchableWithoutFeedback onPress={this.props.onPress}>
(...more code inside)
</TouchableWithoutFeedback>
)
}
}
/////////////////////////////////////////////////////////////////
class Parent extends Component {
pressFunction = () => {
(animate progress from 0 to 1 for some animation)
}
render() {
return this.props.data.array.map(obj => {
return(
<View style={someStyle}>
<MyButton
data={obj}
onPress={this.pressFunction}
/>
</View>
)
})
}
}

How to call componentWillUpdate() to update a child components state?

My toolbar is already rendered and i want to now call componentWillUpdate() on this toolbar when i need to update it's state?
HomeScreen
constructor(){
super();
this.state = {
pagenum: 0,
toptoolbartitle: "default",
homeviewtitle: "default",
};
}
updateHomeViewTitle(viewtitle){
console.log(viewtitle);
this.state.homeviewtitle = viewtitle;
console.log("homeviewtitle is now"+this.state.homeviewtitle);
}
render() {
return (
<View style={styles.container}>
<View style={{flex:1}}>
<TopToolbarAndroid
defaulttitle={"default"} titleupdate={this.state.homeviewtitle}/>
<RNCamera updateviewtitle={this.updateHomeViewTitle.bind(this)} />
<BottomBar />
</View>
</View>
TopToolbarAndroid
constructor(props){
super();
this.props = props;
this.state = {
pagenum: 0,
title: this.props.defaulttitle
};
}
componentWillUpdate(){
console.log("component will update?");
if (this.props.titleupdate != null)
{console.log("updating toolbar title to: "+this.props.titleupdate);
this.setState({title: this.props.titleupdate});}
}
render() {
return (
<ToolbarAndroid
title= {this.state.title}
style={styles.toolbar}
/>
);
}
Result
The componentWillUpdate is not updating the toolbars title, its not being called (re-rendered).
You need not maintain state in TopToolbarAndroid.
Just do this tweak in TopToolbarAndroid to update title-
title={this.props.titleupdate ? this.props.titleupdate : this.props.defaulttitle}
Get rid of this.state too.
I'm not sure what this.props = props does in the constructor. I'd just do super(props).
Let me know, if this doesn't work. Please provide a link to runnable app as well, so that people can solve your problem effectively. Add a tag of react-native to your question to attract the right kind of people.
Host your example here - https://rnplay.org/

Resources