1

There is React component that should be rendered or shouldn't be rendered according to some conditions.
And I can do like follow

class Parent extends React.Component{
  render(){
    {condition() && <Child />}
  }
}

Until now, It's OK, but problem is there are pretty many Parent component in my project.

So I wanna put condition() function in Child Component like following

class Child extends React.Component{
  render(){
    {condition() && <div>Child Component rendered!!</div>}
  }
}

class Parent extends React.Component{
  render(){
    <Chile> {/* type nothing */}
  }
}

But unfortunately, Chile component have ComponentDidMount() function.
And that function do pretty many thing.(like ajax call..)

How can I prevent calling React related functions?(like ComponentXXX...)

Is there any good way?

1
  • Are you going to review the answers on this question?
    – monners
    Commented Feb 13, 2018 at 5:51

1 Answer 1

1

There's no way to prevent a component from firing its component methods as per usual once you've actually rendered the component. As you pointed out, you have to handle whether or not you actually render the component in the first place.

If you don't want the render condition to be in the parent, the easiest thing to do is wrap the child in another, intermediate (or Higher Level) component that handles the conditional. That'd look something this:

// 'ConditionallyRenderChild.jsx'
import React from 'react'
function someCondition () {
  // Return true or false, depending on condition
}

const ConditionallyRenderChild = ({children}) => {
  // If condition is met, render child...
  // ...otherwise return null
  return someCondition() ? children : null
}

export default ConditionallyRenderChild


// `Parent.jsx`
import React, { Component } from 'react'
import ConditionallyRenderChild from './ConditionallyRenderChild'

export default class Parent extends Component {
  render () {
    <div>
      <ConditionallyRenderChild>
        <Child /> {/* This won't render unless condition is met by ConditionallyRenderchild lets it */ }
      </ConditionallyRenderChild>
    </div>
  }
}
1
  • Sorry for being late. I'll try what you have answered. Thank you for answering.
    – JoonT
    Commented Feb 20, 2018 at 7:08

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.