0

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.

stkvtflw
  • 12,092
  • 26
  • 78
  • 155

1 Answers1

3

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.

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
  • Should I go through flux or change state directly in component?? – stkvtflw Aug 11 '15 at 12:09
  • 2
    @stkvtflw You should change the state directly. Flux is for managing data.. like a list of `cars`, a list of `contacts`, the logged in `user`. For state that is view-specific, there's no need for Flux. – Andre Pena Aug 11 '15 at 12:11