Native
This guide assumes that you'll use opam and dune.
Install
opam install styled-ppxPackages available
styled-ppxis the ppxstyled-ppx.css_nativeare the CSS bindingsstyled-ppx.emotion_nativeis a native implementaiton ofemotion.shcapable of storing CSS, hashing it and generating a unique className, autoprefixing, etc.
Usage
Add styled-ppx under dune's preprocess pps for any library or executable. Add styled-ppx.css_native and styled-ppx.emotion_emotion as libraries.
(library
(name ...)
(libraries
+ styled-ppx.css_native
+ styled-ppx.emotion_native
server-reason-react)
(preprocess
(pps
+ styled-ppx
melange.ppx
server-reason-react-ppx)))(melange.emit
(target ...)
(libraries
+ styled-ppx.css
+ styled-ppx.emotion
server-reason-react)
(preprocess
(pps
+ styled-ppx
melange.ppx
server-reason-react-ppx)))Note: server-reason-react and server-reason-react-ppx are optional, and only needed if you use styled components ([%styled.div {||}]).
Example
/* This is a server-reason-react module with those styles encoded as a unique className */
module Link = [%styled.a (~color=CssJs.hex("4299E1")) => {|
font-size: 1.875rem;
line-height: 1.5;
text-decoration: none;
margin: 0px;
padding: 10px 0px;
color: $(color);
|}];
/* This is a unique className pointing to those styles */
let layout = [%cx {|
display: flex;
width: 100%;
height: 100%;
justify-content: center;
align-items: center
|}];
/* Later in a component */
let app =
<div className=layout>
<Link
color={CssJs.hex("333333")}
href="https://sancho.dev"
rel="noopener noreferrer">
{React.string("sancho.dev")}
</Link>
</div>;
let stylesheet = CssJs.render_style_tag(); /* This will render the stylesheet to be present in the head of the document */This can be used in the Page component of your server side rendered React components
module Page = {
[@react.component]
let make = ( ... ) =>
...
<head>
...
<style> {React.string(CssJs.render_style_tag())} </style>
...
</head>
}If you're using dynamic css props, (ie your style components' css relies on dynamic values), make sure to run this function only after the react components are rendered.
Rendering the React components first, gives the React runtime to force out the values from the dynamic css styles which are represented lazily.
Example
module Page = {
[@react.component]
let make = (~appHTMLString) => {
let stylesheet = CssJs.render_style_tag();
<html>
...
<style> {React.string(stylesheet)} </style>
</head>
<body>
<div
dangerouslySetInnerHTML={"__html": appHTMLString}
/>
</body>
</html>;
};
};
let hello_route_handler = _request => {
let appHTMLString =
ReactDOM.renderToString(<Reason_india_website_native.App />);
Dream.html(
ReactDOM.renderToString(
<Page scripts=["/static/app.js"] appHTMLString />,
),
);
};