0

I have the following react component:

            <HashRouter>
            <div className="App">

                {/* Static section */}
                <div>
                    <NavBar title="MyApp" />
                </div>

                {/* Dynamic section */}
                <div>

                    <Route path="//" component={HomePage} />
                    <Route path="/market" component={MarketPage}/>

                </div>

            </div>
        </HashRouter>

And the NavBar component is expecting render children components that will represent the websites content as per Ant designs component. My question is how can I render my child components inside the navbar component without re-rendering the navbar again? I have a {this.props.children} inside the navbar but I don't know where to inject the prop without forcing the navbar to render again.

Vikas Yadav
  • 3,094
  • 2
  • 20
  • 21
ninesalt
  • 4,054
  • 5
  • 35
  • 75
  • If you are passing the children as props then NavBar will re-render. – Chris Jan 24 '18 at 11:33
  • Possible duplicate of https://stackoverflow.com/questions/44734548/what-is-the-children-prop-in-react-component-and-what-proptypes-do/44734573#44734573 – Shubham Khatri Jan 24 '18 at 11:44
  • the way to pass children is like this ` children `. Then you will be able to access `this.props.children` within `NavBar` – aelor Jan 24 '18 at 11:57
  • First of all: Why do you want to send those children from a prop? Can you just add them inside the `NavBar` component? If you really have to send them from a prop, so, you are expecting to re-render the NavBar every time the props change. – Broda Noel May 17 '19 at 18:05

1 Answers1

0

No. If you want to render component A, inside B, and you send A as a prop of B, so, B is going to be re-rendered every time their props change.

If you want to avoid it, you should not send A as a prop, and just render it inside a wrapper component in B.

For example:

// Your NavBar
function NavBar() {
    // This component is not going to be re-rendered, due to is
    // not receiving the children components as props.
    // The childrens are going to be in <Wrapper>
    return (
        <div className="NavBar">
            Hello!<br>

            <Wrapper />
        </div>
    );
}

// Here you have to have a condition to show
// component `ChildA` or `ChildB`.
// You can do that switching with some Redux or Duix value
function Wrapper() {
    return (
        <div className="Wrapper">
            {
                somethingHappened ? <ChildA /> : <ChildB />;
            }
        </div>
    );
}

function ChildA() {
    return(...);
}

function ChildB() {
    return(...);
}

Check that the Wrapper component should be listening some Redux (https://www.npmjs.com/package/react-redux) or Duix (https://www.npmjs.com/package/duix) value to switch between ChildA or ChildB

Broda Noel
  • 1,760
  • 1
  • 19
  • 38