2
votes

How to pass child component class as props to parent component in React.

My Parent component code :

import React, { Component } from 'react';
import { DashBoard } from './DashBoard/DashBoard';
import { DashBoard } from './Details/Details';

class ContentArea extends Component {
  render() {
    return (
      <div className="content-wrapper">
        <DashBoard />
        <Details />
      </div>
    )
  }
}

export default ContentArea;

And my child component code :

import React, { Component } from 'react';

export class DashBoard extends Component {
  render() {
    return (
      <h1>This is DashBoard Page.</h1>
    );
  }
}

And my Route.js code :

import React, { Component } from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';

import { App } from './App';
import { DashBoard } from './components/DashBoard/DashBoard';
import { Details } from './components/Details/Details';


export class AppRoute extends Component {
  render() {
    return (
      <Router>
        <div>
          <Route exact path={'/'} component={App} />
          <Route path={'/DashBoard'} component={DashBoard} />
          <Route path={'/Details'} component={Details} />
        </div>
      </Router>
    );
  }
}

App.js :

import React, { Component } from 'react';

import SideBar from './components/SideBar';
import Footer from './components/Footer';
import Header from './components/Header/Header';
import ContentArea from './components/ContentArea';

export class App extends Component {
  render() {
    return (
      <div className="skin-purple">
        <Header />
        <SideBar />
        <ContentArea />
        <Footer/>
      </div>
    );
  }
}

Now I want to pass my all child component as props to the parent component. And while routing the child component should get render inside the parent component.

Can anyone help me how to achieve that??

1
How does ContentArea relate to App?Harald Gliebe
In my ContentArea, I just want to render my child components based on routing.Riya Kapuria

1 Answers

1
votes

Since ContentArea is in App component and you wish to render DashBoard and Details in it, you could specify nested Routes at ContentArea level.

export class AppRoute extends Component {
  render() {
    return (
      <Router>
        <div>
          <Route path={'/'} component={App} />
        </div>
      </Router>
    );
  }
}


import { DashBoard } from './DashBoard/DashBoard';
import { Details } from './Details/Details';
class ContentArea extends Component {
  render() {
    return (
      <div className="content-wrapper">
        <Route exact path={'/DashBoard'} component={DashBoard} />
        <Route exact path={'/Details'} component={Details} />
      </div>
    )
  }
}

export default ContentArea;