Skip to content

Allow for specifying defaultMatches #50

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 2 commits into from
Apr 11, 2017
Merged

Allow for specifying defaultMatches #50

merged 2 commits into from
Apr 11, 2017

Conversation

edorivai
Copy link
Collaborator

@edorivai edorivai commented Apr 7, 2017

This should be particularly useful for avoiding client/server rendering mismatches.

See #46 for details

edorivai added 2 commits April 5, 2017 17:12
This should ensure backwards compatibility
@mjackson mjackson merged commit 4e2914d into ReactTraining:master Apr 11, 2017
@mjackson
Copy link
Member

Thanks, @edorivai :)

@sedubois
Copy link

Thanks a lot for this. When will it get released? And I didn't get how I should use it?

I need SSR support as I use Next.js.

Thanks a lot

@nezed nezed mentioned this pull request Jun 21, 2017
@edorivai
Copy link
Collaborator Author

I see that the version was bumped, yay 🎉!

@sedubois The idea is that you set the defaultMatches prop while rendering on the server side. By default, defaultMatches is set to true, so depending on how you interpret a match, the component will either always or never be rendered serverside.

We cannot be 100% sure what the client will render, but we can use a heuristic to make an educated guess about what the client will probably render. The heuristic we are using is the user agent. You'll have to come up with a system to pass this heuristic down, but once you do, your rendering code might look like this:

<Media
	query="(max-width: 500px)"
	defaultMatches={isUserAgentSignallingMobile()} // insert your own guessing logic
	render={() => (
		<div className="myMobileStyle">
			Mobile content!
		</div>
	)}
/>

Not sure if it helps you, but we populate our redux store with user agent information before we trigger the React render.

@saeta-eth
Copy link

@edorivai Any example of the isUserAgentSignallingMobile function?

@edorivai
Copy link
Collaborator Author

Using ua-parser-js, you'll have to get the User-Agent header from the incoming request. How you do that depends on the http library you're using (probably express, koa, or hapi or something).

const parser = require('ua-parser-js');

function isUserAgentSignallingMobile(userAgentString) {
    const ua = parser(userAgentString);
    return ua.device.type === 'mobile';
}

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

4 participants