Search code examples
reactjsreactjs-fluxflux

How to render new React Component into rendered DOM?


I have three component parent and 2 childs:

import React from 'react';
import FirstChild from './FirstChild';
import SecondChild from './SecondChild';

export default class ComponentName extends React.Component {
    render() {
        return (
            <div>
                <h1>ComponentName</h1>
                <div id="renderChildHere">
                    <FirstChild />
                </div>
                <button onClick={this.clickHandler}>Replace FirstChild with SecondChild</button>
            </div>
        );
    }

    clickHandler() {
        ???
    }
}

The FirstChild is initially rendered. How do I unmount it and mount the SecondComponent in the #renderChildHere Dom element?

I use React 0.13.3 and Flux without third-party addons.


Solution

  • You should have a state on ComponentName that tells which child component to render. For simplicity, I'm gonna call it childComponentName and it can hold either firstComponent and secondComponent as strings. On your this.clickHandler, you should do something like this:

    this.setState({childComponentName: 'secondComponent'});
    

    Now React is going to render ComponentName again. Within the render method, you can choose whether to render <FirstComponent/> or <SecondComponent/> based on the value of the childComponentName state.

    Of course this is just for simplicity, so you can understand the concept.

    You'll only manually mount and unmount components in very specific scenarios. For all the others, this is the way to go.