3

I have this piece of code (which I've simplified for posting here) that creates a component and renders it

        const getComponentToRender = (user, path) => {
          switch(path ){
            case 'ChangePassword':
              return <ChangePassword user={ user } />;
            case 'NewPassword':
              return <NewPassword user={ user } />;
            case 'PasswordExpire':
              return <PasswordExpire user={ user } />;
            default:
              return null;
          }
         }

        class UserAdmin extends React.Component {  
          static propTypes = {
            user: PropTypes.object.isRequired
          };
          render() {
            const component = getComponentToRender(this.props.user, 'ChangePassword' );          
            return(
                <div id='user-admin-wrapper'>
                  {component}
                </div>
              )

          }  
          componentWillUnmount(){

          }
       }

When I navigate away from UserAdmin the componentWillUnmount gets called.

Q: What is the simplest way to actually remove the component ChangePassword or any other component (by its name) from the DOM when componentWillUnmount executes. OR, removing the component at any point, without waiting for componentWillUnmount

Using react-dom 15.6.1 . btw

Rory
  • 1,442
  • 4
  • 21
  • 38

1 Answers1

1

Un-mounting a component will un-mount(remove) all the child components it contains. So after componentWillUnmount the component you rendered inside it will be removed.

If you need to control over components that rendered without un-mounting you use conditional render logic.

Example

class SomeComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      shouldIRender: true
    };
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({shouldIRender: false});
    }, 5000);
  }
  render() {
    return(
      <div>
        <ComponentThatAlwaysHere />
        { this.state.shouldIRender === true ? <ComponentThatRemovesAfterStateChange /> : null }
        { this.state.shouldIRender === true && <AnotherComponentThatRemovesAfterStateChange /> }
      </div>
    )
  }
}
bennygenel
  • 23,896
  • 6
  • 65
  • 78