Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render different components on client and server side

I am currently developing a website where I have used react, react-router and redux. We are doing Server side rendering and using react router on server as well. Now I have a case where i want client side to render different component than server side. I want like this.

Client Side

<Route path="welcome/:id" component={Home} />

Server Side

<Route path="welcome/:id" component={App} />

I have use case like when user click's an image i want to open a modal with contents and recommend images . when user click's on recommended images same modal should fill up the details and i want to change the route as well. Same route when opened in new window should open an html page for facebook and google to scrap meta tags from it.

So either I render different component on client and server. But that too has a problem because then i need to find a way to turn off client side react router when server is serving the rendered page.

Or in client side generate a pseudo route change which changes url but doesn't render a component.

like image 320
Priyank Bhatt Avatar asked Jul 26 '16 08:07

Priyank Bhatt


People also ask

What are the difference in clients side and server-side rendering?

Client-side rendering manages the routing dynamically without refreshing the page every time a user requests a different route. But server-side rendering is able to display a fully populated page on the first load for any route of the website, whereas client-side rendering displays a blank page first.

Can a component be both a client and a server?

Shared Components are components that can run on both client-side and server-side.

Can React JS render both on client and server side?

js is used for server side rendering of react application . React along with other framework like angular and vue. js are traditional client side framework ,they run in browser but there are technology to run this framework on server side, and next.

Can a component render another component?

A Component in a Render FunctionRender methods can also return another kind of JSX: component instances. In the above example, Crazy 's render method returns an instance of the OMG component class. You could say that Crazy renders an <OMG /> .


1 Answers

Check if window is present and conditionally set the component you want to use like this:

let Handler;

if (typeof window !== 'undefined') {
  Handler = Home;
} else {
  Handler = App;
}

return <Route path="welcome/:id" component={Handler} />

The troublemaker in me wants to know why you're doing this :)

like image 134
David Gilbertson Avatar answered Oct 23 '22 08:10

David Gilbertson