0

This is my example code.

import React, { Component } from "react";
import Navpills from "./Navpills";
import Home from "./pages/Home";
import About from "./pages/About";
import Blog from "./pages/Blog";
import Contact from "./pages/Contact";

class PortfolioContainer extends Component {
  state = {
    currentPage: "Home"
  };

  handlePageChange = page => {
    this.setState({ currentPage: page });
  };

  render() {
    return (
      <div>
        <Navpills
          currentPage={this.state.currentPage}
          handlePageChange={this.handlePageChange}
        />
        Based on `this.state.currentPage`, render the appropriate component
        here.
      </div>
    );
  }
}

export default PortfolioContainer;

The instructions are as follows:

Now add code to PortfolioContainer so that depending on the currently selected page, a different component is rendered underneath the Navpills component. Example:

  • Render the About component when this.state.currentPage === "About"

  • Render the Blog component when this.state.currentPage === "Blog"

  • Render the Contact component when this.state.currentPage === "Contact"

  • Render the Home component when this.state.currentPage === "Home"

2
  • there is a page in the documentation for this reactjs.org/docs/conditional-rendering.html Commented Jan 9, 2018 at 18:34
  • Also, welcome to stackoverflow. You didn't really ask a question, but pasted something like a homework assignment? check out this page for how to ask a good question stackoverflow.com/help/how-to-ask Commented Jan 9, 2018 at 18:35

2 Answers 2

1

You can use the following syntax to conditionally render a component:

render() {
    return (
      <div>
        <Navpills
          currentPage={this.state.currentPage}
          handlePageChange={this.handlePageChange}
        />
        {this.state.currentPage === "About" && <About />}
        here.
      </div>
    );
  }

But in your case it might be better to use react-router.

Sign up to request clarification or add additional context in comments.

1 Comment

From what I understand, the code in the question is just for learning purposes. If it is an actual application, you should definitely use react-router.
0

There are a few ways to do it React docs has an example here : https://reactjs.org/docs/conditional-rendering.html

There is also this package: https://www.npmjs.com/package/react-render-if

Or you can do this terse way of : {this.state.currentPage === "About" && < About />}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.