Reputation: 1281
I am developing an react js app using functional components.
I am trying to reuse components in the code. I have a component Frame
which has Sider and Header. I am trying to add Content
component to that frame to display in the middle, but its not working though.
Frame.tsx
const Frame : React.FC = (props) => {
const [collapsed, onCollapse] = useState(false);
const Content = props.content;
console.log('Content: ',Content);
return (
<Layout>
<SideBar state={{ collapsed: [collapsed, onCollapse]}}/>
<Layout>
<HeaderBar state={{ collapsed: [collapsed, onCollapse]}}/>
{Content}
<Footer>footer</Footer>
</Layout>
</Layout>
);
}
export default Frame;
PublicRoute.tsx
interface PublicRouteProps extends RouteProps {
// tslint:disable-next-line:no-any
component: any;
isAuthorized: boolean;
content: Content;
}
const PublicRoute = (props: PublicRouteProps) => {
const { component: Component, isAuthorized, content: Dummy, ...rest } = props;
return (
<Route
{...rest}
render={(routeProps) =>
isAuthorized ? (
<Component {...routeProps}/>
) : (
<Redirect
to={{
pathname: '/login',
state: { from: routeProps.location }
}}
/>
)
}
/>
);
};
export default PublicRoute;
App.tsx
return (
<BrowserRouter>
<div>
<Switch>
<PublicRoute path="/" component={Frame} exact isAuthorized={true} content={Dummy}/>
<Route path="/login" component={NewLogin} exact isAuthorized={true}/>
</Switch>
</div>
</BrowserRouter>
);
I am not able to pass contents dynamically and I am not sure whats wrong. Thank you for your time.
Upvotes: 1
Views: 2602
Reputation: 21
I guess we can use the createElement function in place of {content}.
{React.createElement("NewLogin");}
Upvotes: 0
Reputation: 379
You have to pass to the component with <Content />
otherwise it won't be instantiated.
Here's a full example
import React from "react";
import "./styles.css";
function Parent({content}) {
return (
<div>
{content}
</div>
)
}
function Content() {
return (
<h1>Hello</h1>
)
}
export default function App() {
return (
<div className="App">
<Parent content={<Content/>} />
</div>
);
}
Upvotes: 2
Reputation: 150
You pass the components like so: .
Try something like this:
return (
<BrowserRouter>
<div>
<Switch>
<PublicRoute path="/" component={<Frame />} exact isAuthorized={true} content={<Dummy />}/>
<Route path="/login" component={<NewLogin />} exact isAuthorized={true}/>
</Switch>
</div>
</BrowserRouter>
);
Upvotes: 1