React making components out of elements - javascript

I am currently putting together elements of my website but making react components out of them.
Here's a button for example:
import React from 'react';
class Button extends React.Component {
render() {
return <button className={this.props.bStyle}>{this.props.title}</button>;
}
}
export default Button;
I have lots of other elements to put into react components so there's going to be a large list of them.
The problem is that what you have lots of them and you need to import all the list can really grow too big.
Just imagine 50 of these:
import Element from './Element.component'; // x50 ?
My question is...Is their a better approach to importing large lists of components in React?

You can import all of your elements to one file and export all individually. Then you are able to import all as elements and use as elements.someComponent.
// common.js because you ll commonly use them
import Element from './Element.component';
import Element2 from './Element.component2'; // x50 ?
/* ... */
export { Element, Element2 /* ... */ };
// in someOtherFile.js
import * as Elements from './common';
/*
now you are able to use these common elements as
<Elements.Element />
<Elements.Element2 />
...
*/

Related

having access to a parent state from component's props.children:

I am making a container for a d3 line graph that I'm going to create, my format so far is this:
import React from "react";
import AnalyticPads from "../AnalyticPad/AnalyticPad";
import Pad from "../AnalyticPad/Pad";
import MainContent from "../AnalyticPad/MainContent";
import Extention from "../AnalyticPad/Extention";
const GraphPad = () => {
return (
<AnalyticPads properties={{height: "200px"}}>
<Pad>
<MainContent>
</MainContent>
<Extention>
</Extention>
</Pad>
</AnalyticPads>
)
}
export default GraphPad;
And my "AnalyticsPad" looks like this:
import React from "react";
const AnalyticPads = (props) => {
return (
<div className="analytic-pad-container">
{props.children}
</div>
)
}
export default AnalyticPads;
What I want is that there will be a grid of "Pads" and I want this "AnalyticsPad" to provide default styles for each pad, for example if I want each pad to have a height of 200px I set it in this wrapper and then for any individual pad that I want to differ from the default I can overide it.
The "MainContent" component is where the line graph will be and any extra information will be put inside the "Extention" which will render if a button is pressed.
Throughout my react app I keep using the context api to provide the data to the children components, but I know ( or think ) it is bad practice to do this, from what I understand context should only be used for providing data to global components.
What is best practice?
please don't answer with a solution for class components as I have never used them before as I am new to react.

How to wrap every exported comopnent with HOC?

I need to add to ALL of my React function components the possibility to add [data-test-id] attribute for testing purposes. To achieve that I created withTestId() HOC which adds optional prop testId to wrapped component and when it's defined it adds [data-test-id] to final HTML.
So when I define component like:
<ExampleComponent testId="example" />
it returns:
<div data-test-id="example" />
The only problem I have is to apply it to every component without the necessity to wrap it individually in every component. So instead of writing code like:
function ExampleComponent() { ... }
export default withTestId(ExampleComponent)
I would like to wrap all of my exports in my index.ts file, which right now looks like this:
export { default as ExampleComponent } from "./ExampleComponent";
export { default as ExampleComponent2 } from "./ExampleComponent2";
...
How can I achieve this?
I see two ways of doing this; One dynamic way, making the user-code of your library a bit more convoluted. with you being able to change the implementation easily and another one with a bit more boilerplate code, keeping the user-code as it is.
I haven't tested their behavior regarding tree-shaking when bundling the code.
Using destructing in user-code
This allows to add / remove things from your main component export file without having to worry about additional boilerplate in your library. The higher-order-component can be switched on/off easily. One caveat: The user code needs to use destructuring to retrieve the components.
Your new index.ts file would look like this, while I've called your previous index.ts file components.ts in the same directory:
import * as RegularComponents from "./components";
import withTestId from "./with-test-id";
const WithTestIdComponents = Object
.keys(RegularComponents)
.reduce((testIdComps, key) => {
return {
...testIdComps,
[key]: withTestId(RegularComponents[key])
};
}, {});
export default WithTestIdComponents;
To use it in your application code:
import MyComponents from "./components/tested";
const { Component1, Component2, Component3, Component4 } = MyComponents;
This uses the default export to make it look like you have all components in one place, but since you cannot destructure exports directly, you need this second step to get the correct components out of it.
Add boilerplate to the export file
Since there is an index.ts file with all the components exported in the library, one could import/rename each component and re-export them with withTestId and their name:
import withTestId from "./with-test-id";
import { default as TmpComponent1 } from "./component1";
import { default as TmpComponent2 } from "./component2";
import { default as TmpComponent3 } from "./component3";
import { default as TmpComponent4 } from "./component4";
export const Component1 = withTestId(TmpComponent1);
export const Component2 = withTestId(TmpComponent2);
export const Component3 = withTestId(TmpComponent3);
export const Component4 = withTestId(TmpComponent4);
This way, imports can be used as before:
import {
Component1,
Component2,
Component3,
Component4
} from "./components";
I'd argue that using index files already is some kind of boilerplate and this approach adds to it. Since the user code does not need any changes, I'd favor this approach.
In one of our projects, we have used a custom takeoff script to create this kind of boilerplate for us, whenever we generate a new component.
Examples
Here is a code sandbox to see both approaches.

Can you import a file which already contains reactDOM render calls?

I have a legacy enterprise application which contains numerous components which are rendered to multiple anchor points on the page. example below
modals.js
import etc
class MyModal extends Component {
render() {
return <span>a modal</span>
}
}
var modals = $('.react__modal');
if (modals.length) {
modals.each(function() {
ReactDOM.render(<MyModal />,this);
});
}
now suppose I have multiple areas to this app such as admin.js, frontend.js, account.js, could I import modals.js in some what to be included within all these areas or would I have to export the class and then have multiple declarations of my ReactDOM.render in each of my areas.
I have approximately 100 components like this, and I'd rather not have to duplicate the render across all areas (6 in total).
Currently using gulp to compile, but in the process of moving to webpack (using laravel mix).
You could try to use export:
export default class MyModal extends Component
Then in other components you can import it and use:
import MyModal from "./yourPathToComponent"

Code snippet inside Highlight component displays in a long single line

Code snippet inside Highlight component displays in a long single line.
How to add multiple line codes inside an Highlight component?
Assuming you are using react-highlight, the easiest way is probably to use <br>'s. It seems like using the innerHTML prop should also be an option, but from my (limited) testing, that functionality appears buggy.
import React, {Component} from 'react';
import Highlight from 'react-highlight';
class App extends Component {
render() {
return (
<div>
<Highlight language='javascript'>
const varOnLine1 = "abc";<br/>
const varOnLine2 = "def";<br/>
const varOnLine3 = "ghi";
</Highlight>
</div>
);
}
}
export default App;

import or require React components dynamically

I'm trying to import / require components dynamically, but somehow when I do it React complains. The require function does find it, but React throws an error saying it is missing some functions 't' etc.. All of this in an electron app.
I have a wizard setup (that is working, but not so elegant I think), where each page has it's own layout and jsx component. If I'd like to add a new page, I don't want to manage x-number of files, and at the moment I have to due to the setup I have currently. Below you can find what I want to achieve and what I'm doing now to achieve it. If there are any suggestions, code smells or better options please let me know as I'm quite new to React and ES2015 (as I'm from a C# background).
What I'm trying to achieve
export default class WizardPageContainer extends Component {
// Constructor
constructor(props) {
super(props);
}
// Render
render() {
const WizardPage = require(`./path/to/${this.props.step.id}`);
return (
<WizardPage step={this.props.step} />
);
}
}
How I'm currently doing it : which means I have to declare the imports / files first on top of the "WizardPageContainer" component.. Which means extra work and prone to errors/forgetting things. I should add, this code is working now ok, but I don't think this is elegant/future proof:
/* PAGES */
import WizardPage_Welcome from './pages/0.wizard.welcome';
import WizardPage_SystemCheck from './pages/1.wizard.systemCheck';
import WizardPage_SignIn from './pages/2.wizard.signIn';
import WizardPage_ExamCode from './pages/3.wizard.examCode';
import WizardPage_TakeExamination from './pages/4.wizard.takeExamination';
import WizardPage_Close from './pages/5.wizard.close';
const pages = [
WizardPage_Welcome,
WizardPage_SystemCheck,
WizardPage_SignIn,
WizardPage_ExamCode,
WizardPage_TakeExamination,
WizardPage_Close
];
/*/********************************************************************///
/* ******************************************************************** */
/* COMPONENT */
export default class WizardPageContainer extends Component {
// Constructor
constructor(props) {
super(props);
}
// Render
render() {
const WizardPage = pages[`${this.props.step.id}`];
return (
<WizardPage step={this.props.step} />
);
}
}
/*/********************************************************************///
I think it is about the "default". i have problem like this. Can you check this code;
https://github.com/robeio/robe-react-admin/blob/master/src/app/HasAuthorization.jsx#L10
Also you can check the example usage;
https://github.com/robeio/robe-react-admin/blob/master/src/app/HasAuthorization.jsx#L26
Your const pages needs to be an object, not an array.
You can see a working version I made of this here:
https://github.com/Frazer/meteor-react-nav/blob/master/lib/jsx/App.jsx
Best advice: Use Webpack to handle your imports, it's way more efficient than we could ever be.

Categories

Resources