Using renderToNodeStream with react-rails / webpacker - styled-components

I'm working on an app using react-rails / webpacker, with a rails server and React frontend. On top of this, we are also using styled-components and have overwritten the existing ReactRailsUJS.serverRender method in the app/javascript/packs/server_rendering.js file to account for styled components as the following (see https://github.com/reactjs/react-rails/issues/864#issue-291728172 for more info):
// server_rendering.js
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { ServerStyleSheet } from 'styled-components';
const componentRequireContext = require.context('components', true);
const ReactRailsUJS = require('react_ujs');
ReactRailsUJS.useContext(componentRequireContext);
ReactRailsUJS.serverRender = function(renderFunction, componentName, props) {
const ComponentConstructor = this.getConstructor(componentName);
const stylesheet = new ServerStyleSheet();
const wrappedElement = stylesheet.collectStyles(
<ComponentConstructor {...props} />
);
const text = ReactDOMServer[renderFunction](wrappedElement);
// prepend the style tags to the component HTML
return `${stylesheet.getStyleTags()}${text}`;
}
This all works well, since the renderFunction param passed as the first argument of the ReactRailsUJS.serverRender function is react-dom/server's renderToString method. However, we would like to update the application to use the renderToNodeStream method for rendering our react components, which is what brings me to this discussion.
I was wondering if there is anyone out there with some more in depth knowledge of how these libraries work at a more core level to help me figure out how we might be able to use renderToNodeStream, given our application setup.
Any advice / direction is appreciated, and I can provide additional information if necessary. Thank you for the consideration and help!

Related

How to map dynamic routes to components outside pages folder in a NextJs multi tenant application

I am following this template here to create a Multi-tenant application using NextJS.
However, I am stucked at how to properly resolve the routing of the pages.
My pages folder is structured in this manner
pages/
_sites/[site]
[path.jsx]
index.jsx
I have the routing logic inside[path.jsx] file above
I have moved all my components from the pages folder to another folder called components.
Now, when a user visits for example james.mydomain.com/blog I wish to load the blog component from the components folder.
How can that be neatly done without too much hardcoding?
Here is what I have attempted but the page only freezes without loading the component:
import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import Loading from "react-loading";
export default function SiteComponent(props) {
const router = useRouter();
const [component, setComponent] = useState(null);
const { path } = router.query;
const loadComponent = async (path) => {
const importedComponent = await import(`../../../src/components/${path}`);
setComponent(importedComponent.default);
}
useEffect(() => {
if (path) {
loadComponent(path);
}
}, []);
return (
component ? <component /> : <Loading color="teal" type="bubble" />
);
}
Is there a way to do this neatly without the above dynamic component loading?
I feel the above code may not even work properly on the occasion I wish to load a nested route eg. james.mydomain.com/blog/categories.
Please kindly suggest a cleaner approach.

Adminjs ComponentLoader not found

I have been trying to make custom component in Adminjs 6.6.5 dashboard but Adminjs ComponentLoader not found error occurs. then i have tried to
import AdminJS from 'adminjs'
const {ComponentLoader} = AdminJS
but i get: Trying to bundle file 'file:/Users/Josip/WebstormProjects/ferry-backend/components/dashboard.jsx' but it doesn't exist
I would really appreciate help...
admin/index.js
import {ComponentLoader} from "adminjs";
const componentLoader = new ComponentLoader()
const Components = {
MyDashboard: componentLoader.override('Dashboard','../components/dashboard.jsx')
}
export { componentLoader, Components }
index.js
import {componentLoader, Components} from "./admin/index.js";
AdminJS.registerAdapter(AdminJSSequelize)
const admin = new AdminJS({
databases: [],
rootPath: '/admin',
resources:[UsersResources, GuestResources, SalesResources, FinancesResources],
components:{
edit: Components.MyDashboard
},
componentLoader
})
you are fixed this problem? I also ran into this problem and don't understand how to solve it
i fixed this problem. You need to do the import as follows
import AdminJs from 'adminjs';
// And now you can use any adminjs dependencies as follows
AdminJs.ValidationError(errors)
My usage example:
if(Object.keys(errors).length) {throw new AdminJs.ValidationError(errors)} else {...}
Good luck with your development!

React: add HTML from generic file path at server-side build time

The use case I'm trying to fulfill:
Admin adds SVG along with new content in CMS, specifying in the CMS which svg goes with which content
CMS commits change to git (Netlify CMS)
Static site builds again
SVG is added inline so that it can be styled and/or animated according to the component in which it occurs
Now - I can't figure out a clean way to add the SVG inline. My logic tells me - everything is available at build time (the svgs are in repo), so I should be able to simply inline the svgs. But I don't know how to generically tell React about an svg based on variables coming from the CMS content. I can import the svg directly using svgr/weback, but then I need to know the file name while coding, which I don't since it's coming from the CMS. I can load the svg using fs.readFileSync, but then the SVG gets lost when react executes client-side.
I added my current solution as an answer, but it's very hacky. Please tell me there's a better way to do this with react!
Here is my current solution, but it's randomly buggy in dev mode and doesn't seem to play well with next.js <Link /> prefetching (I still need to debug this):
I. Server-Side Rendering
Read SVG file path from CMS data (Markdown files)
Load SVG using fs.readFileSync()
Sanitize and add the SVG in React
II. Client-Side Rendering
Initial Get:/URL response contains the SVGs (ssr worked as intended)
Read the SVGs out of the DOM using HTMLElement.outerHTML
When React wants to render the SVG which it doesn't have, pass it the SVG from the DOM
Here is the code.
import reactParse from "html-react-parser";
import DOMPurify from "isomorphic-dompurify";
import * as fs from "fs";
const svgs = {}; // { urlPath: svgCode }
const createServerSide = (urlPath) => {
let path = "./public" + urlPath;
let svgCode = DOMPurify.sanitize(fs.readFileSync(path));
// add id to find the SVG client-side
// the Unique identifier is the filepath for the svg in the git repository
svgCode = svgCode.replace("<svg", `<svg id="${urlPath}"`);
svgs[urlPath] = svgCode;
};
const readClientSide = (urlPath) => {
let svgElement = document.getElementById(urlPath);
let svgCode = svgElement.outerHTML;
svgs[urlPath] = svgCode;
};
const registerSVG = (urlPath) => {
if (typeof window === "undefined") {
createServerSide(urlPath);
} else {
readClientSide(urlPath);
}
return true;
};
const inlineSVGFromCMS = (urlPath) => {
if (!svgs[urlPath]) {
registerSVG(urlPath);
}
return reactParse(svgs[urlPath]);
};
export default inlineSVGFromCMS;

React Redux - Error passing several store enhancers to createStore()

I have a react app running redux and thunk which has all been working fine. I need to persist the store state on page reload so that data is not lost, so have created a function which is storing data in the localstorage and then returning the data ready for adding to createStore (https://stackoverflow.com/a/45857898/801861). The data storage is working fine and returning the object ready for setting the sate. When adding the data object at createStore react fails to compile with this error:
Error: It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function
Here is CURRENT CODE RETURNING ERROR:
const store = createStore(reducers, LoadState, applyMiddleware(thunk) );
//Error: It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function
My original code which was running:
const store = createStore(reducers, applyMiddleware(thunk) );
I attempted to fix this following some similar issues I found online, compiles but breaks site code which was originally working fine:
const composeEnhancers = LoadState || compose;
const store = createStore(reducers, composeEnhancers( applyMiddleware(thunk) ) );
//Error: Actions must be plain objects. Use custom middleware for async actions.
Not sure what I need to change to get this to work, any help is appreciated.
I think you are following a tutorial which is performing tasks in a previous version of redux.
You need to create a composeEnhancer which will take in your Redux Dev Tools extension as shown
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
after importing compose from 'redux' obviously as shown -
import {createStore, compose, applyMiddleware} from 'redux';
and then, you can create the store as shown -
const Store = createStore(rootReducer, composeEnhancer(applyMiddleware(thunk)))
The error is self-explanatory. It tells you what to do exactly!!
Namely it tell you that you should compose your enhancers instead.
Here is how to it:
Step #1: Import 'compose' from redux library
import { createStore, applyMiddleware, compose } from 'redux';
Step #2: Compose your list of enhancers since you have more than one
const enhancers = [LoadState, applyMiddleware(thunk)];
const store = createStore(
reducers,
compose(...enhancers)
);
Refer to this page for more details.
I suspect your issue is within your LoadState. What ever is it? Here is a working createStore:
const store = createStore(
reducers,
{ counter: { count: 5 } },
applyMiddleware(() => dispatch => {
console.log('Yoyoyo')
return dispatch;
}));
Hope it solves your issue. Make sure to put actual initial state values and not some function or what ever it is LoadState is :)
You can use a package to persist the redux store into the local storage and you don't need to make your own function:
https://github.com/rt2zz/redux-persist
In the first example of the package you can see how to use the persistReducer() and persistStore() to save your state and then auto rehydrates on refresh page.
plz check this advanced store setup that may help you
enter link description here
https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup
import { createStore, applyMiddleware, compose } from 'redux';
+ const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
+ const store = createStore(reducer, /* preloadedState, */ composeEnhancers(
- const store = createStore(reducer, /* preloadedState, */ compose(
applyMiddleware(...middleware)
));
Am starting out with it React-Redux and faced the same issue. am not sure if it is the right approach but here we go.
the one issue you only need to fix in your code is to call the function,
store = createStore(reducers, LoadState(), applyMiddleware(thunk) );
this solution worked for me.
For redux saga users,
import createSagaMiddleware from "redux-saga";
const sagaMiddleware = createSagaMiddleware();
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(rootReducer, composeEnhancer(applyMiddleware(sagaMiddleware)))
import { applyMiddleware, compose, createStore } from "redux";
import { devToolsEnhancer } from "redux-devtools-extension";
import { logger } from "./middlewares/logger";
import reducers from "./reducers";
import { todoReducer } from "./todoReducer";
const store = createStore(
reducers,
compose(applyMiddleware(logger), devToolsEnhancer({ trace: true }))
);
export default store;

Testing React Router with Jest and Enzyme

My goal is to test my React Router Route exports in my app and test if it is loading the correct component, page, etc.
I have a routes.js file that looks like:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import { App, Home, Create } from 'pages';
export default (
<Route path="/" component="isAuthenticated(App)">
<IndexRoute component={Home} />
<Route path="create" component={Create} />
{/* ... */}
</Route>
);
Note: isAuthenticated(App) is defined elsewhere, and omitted.
And from what I've read, and understood, I can test it as such:
import React from 'react';
import { shallow } from 'enzyme';
import { Route } from 'react-router';
import { App, Home } from 'pages';
import Routes from './routes';
describe('Routes', () => {
it('resolves the index route correctly', () => {
const wrapper = shallow(Routes);
const pathMap = wrapper.find(Route).reduce((pathMapp, route) => {
const routeProps = route.props();
pathMapp[routeProps.path] = routeProps.component;
return pathMapp;
}, {});
expect(pathMap['/']).toBe(Home);
});
});
However, running this test results in:
Invariant Violation: <Route> elements are for router configuration only and should not be rendered
I think I understand that the issue might be my use of Enzyme's shallow method. I took this solutions from this SO question. I believe I understand that it is attempting to parse through the wrapper in search of a Route call, putting each into a hashtable and using that to determine if the correct component is in the table where it should be, but this is not working.
I've looked through a lot of documentation, Q&A, and blog posts trying to find "the right way" to test my routes, but I don't feel I'm getting anywhere. Am I way off base in my approach?
React: 15.4.2
React Router: 3.0.2
Enzyme: 2.7.1
Node: 6.11.0
You can't directly render Routes, but a component with Router that uses routes inside. The answer you pointed to has the complete solution.
You will probably also need to change the browserHistory under test environment to use a different history that works on node. Old v3 docs:
https://github.com/ReactTraining/react-router/blob/v3/docs/guides/Histories.md
As a side note, what's the point of testing Route which I assume is already tested in the library itself? Perhaps your test should focus on your route components: do they render what they should based on route params? Those params you can easily mock in your tests because they're just props.
I'm telling you this because in my experience understanding what to test was as important as learning how to test. Hope it helps :)

Resources