afkatja afkatja - 2 months ago 12
React JSX Question

Dynamically render react component based on parent state

My parent component, basically a form, has a child, an overlay with a loader, which only has to be displayed based on parent's state.

import React from 'react';
import Overlay from './overlay';

export default class RegisterForm extends React.Component {
constructor {
this.state = {
loading: false
};
}
handleSubmit(){
this.state.loading = true;
...
}

render(){
return(
<form onSubmit={() => this.handleSubmit()}>
...
<Overlay />
</form>
);
}
}


How can I achieve this?

I tried
React.cloneElement(<Overlay />, {})
but I don't know how to re-append this child to the parent and as I understand, it's not the React-way of doing things...

I also tried setting a
prop
ob
Overlay
based on
state
of the parent, like
React.cloneElement(<Overlay />, { visible = this.state.loading })
but cannot seem to get it to work...

Answer

Make use of ternary operator to render you component. React JSX supports If-else logic for rendering like {(this.state.loading == false) ? <Overlay /> : null}

You should use this.setState({loading: true}); to change state instead of a direct assignment. Also use event.preventDefault() in your handleSubmit();

import React from 'react';
import Overlay from './overlay';

export default class RegisterForm extends React.Component {
  constructor {
    this.state = {
      loading: false
    };
  }
  handleSubmit(event){
   event.preventDefault();
    this.setState({loading: true});
    ...
  }

  render(){
    <form onSubmit {()=>{this.handleSubmit()}>

     {(this.state.loading == false) ? <Overlay /> : null}
    </form>
  }
}
Comments