Proteeti Prova
Proteeti Prova

Reputation: 1169

Rendering different elements conditionally in React.js

I have a react component named JourneyTripComponent. I want to use it in a page where I don't want to render a Row element which is inside this component.

 <Container>
          <Row>
            <CustomColumn sm={8}  padding={"20px 0px 5px 0px"} >
              <Text size={2} color={"#4A494B"} >
                {intl.formatMessage(messages.subHeader)}
              </Text>
            </CustomColumn>
          </Row>
        </CustomColumn>
      </Row>
     </Container>

I want to render the Row with subHeader. I understand that I need to add some conditions to my props but not quite sure how to do it being new to reactjs. Any help on this?

Upvotes: 0

Views: 253

Answers (2)

G_S
G_S

Reputation: 7110

You can do something like this.

For suppose your JourneyTripComponent component (as mentioned in your question) is

Note the 'this.props.showHeader' condition added to <Row>

export class JourneyTripComponent extends React.Component{
  render(){
    return(
      <Container>
      <Row spacing={"40px"} >
        <CustomColumn sm={12} padding={"20px 0px 40px 0px"}>
          <Row className="justify-content-between" >
            <Text size={3.5} color={"#4A494B"} inline >
              {intl.formatMessage(messages.header)}
            </Text>
            <MediaQuery query="(min-width: 768px)">
              {
                this.props.home ? <Anchor
                  size={1.6}
                  color="#79C142"
                  padding={"10px 0px 0px 0px"}
                  to="about-us"
                  inline
                >
                  {intl.formatMessage(homeMessage.section4_learnMore)} <LearnMoreIcon />
                </Anchor>
                  : null
              }
            </MediaQuery>
          </Row>
          {this.props.showHeader && <Row>
            <CustomColumn sm={8}  padding={"20px 0px 5px 0px"} >
              <Text size={2} color={"#4A494B"} >
                {intl.formatMessage(messages.subHeader)}
              </Text>
            </CustomColumn>
          </Row>}
        </CustomColumn>
      </Row>
     </Container>
    )
  }
}

You can use this component in your parent component as

export class MyParentComponent extends React.Component{

render(){
  return(
    <JourneyTripComponent showHeader={false} />
  )
 }
}

Upvotes: 1

Prithviraj Sahu
Prithviraj Sahu

Reputation: 214

You can pass something like props.showSubHeader, and while rendering, only show Row with subHeader if props.showSubHeader is true.

...
{props.showSubHeader && 
  <Row>
    <CustomColumn sm={8}  padding={"20px 0px 5px 0px"} >
      <Text size={2} color={"#4A494B"} >
         {intl.formatMessage(messages.subHeader)}
      </Text>
    </CustomColumn>
  </Row>}

Upvotes: 1

Related Questions