React export components based on folder structure - reactjs

I created a private repo so I can reuse it in my projects. In my frontend app, I want to import the components based on their specific folder structure. Basically this my structure in my reusable repo:
- components
- dialogs
- ResponseDialog.js
- ConfirmationDialog.js
- form
- BaseTextField.js
- BaseSelect.js
- helpers
- date.js
- string.js
In my frontend I want to import it like this:
import { BaseTextField } from '#my-repo/components'
import { date } from '#my-repo/helpers'
I also want to include material ui there and I want to import it like this:
import { Button } from '#my-repo/mui/core'
instead of
import { Button } from '#mui/core';
I want this structure so I don't need to import all the material ui related repo every single time and also my components are just material ui components with modifications

You need to learn about jsconfig.json file.
Here is the reference

Related

Can I use regular bootstrap toast in reactjs?

I tried to understand how to use toast, but I couldn't and that's why I'm looking for help here.
Is there a reason why to use react-bootstrap over regular bootstrap? I start to think that I cannot use all functionalities from regular bootstrap in react
You can use all the plain bootstrap utilities in React, but it is not reccomended.
This is because to enable interactive functionality, Bootstrap uses JQuery and other DOM-altering Javascript, which doesn't always play that well with React, which likes to "own" the DOM and any alterations.
If you check out the Usage section of the Bootstrap Toasts docs (here), you can see that it toasts need to be initialised with Jquery/JS:
Initialize toasts via JavaScript:
$('.toast').toast(option)
This can be messy to place within React, there are ways of calling it inside a useEffect() block but I've had trouble with similar things in the past.
This is why react-bootstrap is great, it can give you pre-made components with all this functionality baked in, which you can just drop into your codebase.
See the react-bootstrap docs for toasts here, fullly funcitonal toasts can be added with just:
<Toast>
<Toast.Header>
<strong className="mr-auto">Bootstrap</strong>
</Toast.Header>
<Toast.Body>Hello, world! This is a toast message.</Toast.Body>
</Toast>
It depends on which version of Bootstrap you're using. Bootstrap 5 no longer uses jQuery so Bootstrap components like the Toast can be used without the need for a 3rd party library like react-bootstrap or reactstrap.
First import the desired components...
import { Toast } from 'bootstrap';
Then, instantiate and use as needed...
const { Toast } = bootstrap;
var toastEl = document.getElementById('myToast');
const bsToast = new Toast(toastEl);
bsToast.show();
Bootstrap 5 Toast with React

Can I live preview React components in VSCode?

New to React. I have been using live server for html files in VS Code but I can't seem to find the same functionality for React components (.js files). Maybe it's obvious or I'm looking for the wrong thing.
I'd like to make changes in the component, especially MUI styling and see the incremental results in a live preview, rather than the entire application having to refresh and click back to the form I'm working on. Any thoughts or suggestions? Thanks.
You don't have to change your code when using storybook. You just have to write new files, that import your component. Then you can pass it fake props to see how it behave depending in many scenarios. If you use create-react-app, it super easy to install, if you have your own config, then your level is good enough to follow their tutorial. The files are formatted like this: MyComponent.stories.js . Then storybook will look at all files that contains "stories" in their name, and launch them on port 6006 when you write yarn/npm run storybook in your terminal. I highly recommend storybook, it is used by most of companies.
Couldn't find a satisfactory solution and not willing to invest too much. Storybook looks like I'd have to change my code and because I'm still relatively new to react, not sure I'm up for that.
I'm just letting VSCode restart server each time I save a change then going to the browser and clicking through the menus to get to the page I'm working on.
For more complex ui changes, I'll create a code sandbox mini react app and just work on that for, like css changes, etc.
UPDATE:
I've implemented Storybook and I like it. After following the doc to install it I saw that I just needed to create a file (story) for a component like MyComponent.stories.js and put in the few lines of code to import and use it, passing in whatever props I wanted to see.
I decided to put my stories files into a separate separate stories folder under src. Here's an example for a Details component:
import React from 'react';
import { action } from '#storybook/addon-actions';
import Details from '../Details';
// How to display the component in Storybook page
export default {
title: 'Details',
component: Details,
// Our exports that end in "Data" are not stories.
excludeStories: /.*Data$/
};
// Props passed into component
export const recordData = {
record: {
id: '1',
createdOn: '2020-04-20 4:07 PM',
createdBy: 'dgarv',
modifiedOn: '2020-04-20 4:07 PM',
modifiedBy: 'dgarv',
}
};
// Use the actual component
export const Default = () => <Details {...recordData} />;
I've developed an extension named AutoPreview that you can use it to preview React/Vue component in VS Code.
You can get it in extension market: https://marketplace.visualstudio.com/items?itemName=jawei.autopreviewer&ssr=false#overview
You can use Preview.js to see the rendered code - https://previewjs.com/docs/platforms/vscode

Files structure with styled component and CRUD

I do want to have a file structure by feature. But I'm using Styled Component and I have a lot of files.
For exemple in my project directory, which is an entity in my application, I have:
Projects.js ProjectList.js ProjectCreate.js ProjectShow.js Card.js CardHeader.js CardBody.js CardFooter.js TasksCounter.js ProjectDescription.js CardAdd.js ProjectDelete.js actions.js reducer.js saga.js constants.js
I could have more files but my pages are still under construction so I could add some more later. Should I split those files again? To have for example sub directories like Projects ProjectCreate ProjectShow put the common files in the root project directory and specific files into those three?
project
|_Projects
|_index.js
|_ProjectList.js
|_Card.js
|_CardHeader.js
|_CardBody.js
|_CardFooter.js
|_TasksCounter.js
|_ProjectDescription.js
|_CardAdd.js
|_actions.js
|_reducer.js
|_saga.js
|_ProjectCreate
|_index.js
|_Form.js
|_actions.js
|_reducer.js
|_saga.js
|_ProjectShow
|_index.js
|_ProjectHeader.js
|_ProjectContent.js
|_actions.js
|_reducer.js
|_saga.js
I saw a lot of different approaches in more than a dozen of tutorials but the examples are always really simple with just a couple of features.
Better solution maybe, using Ducks and put every Styled Components in the same file?
I usually make a separate folder called views for every react (custom) component.
views
- Cards
- index.js
- module.js
- test.js
- styles.js
- Button
- InputFields
- ...
- ...
Inside each view, notice that there is an index.js that has the react component. The module.js will contain reducers and actions if any. test.js will have tests regarding that component only and finally styles.js or styles.css/scss will have styles

importing image with es6 import or require during runtime

I have this image folder:
- country
- EN
- FR
- IT
I want to import an image this way:
import image from "./country/{country}/test.png";
How can I do this?
i will always use both of the methods (require, import).
first thing is i do categorise images in 2 ways:
what i am using so may times and using it frequently.
what is rarely used.
then i will create an js file in that i do import all 1'st kind of images (frequently used). When project will load it will execute all import statements first so that time my all of the images are imported already so then whenever i need this images i do get that image from utility what i have created for importing images. that util file will be kind of this:
import CSK from "../assets/images/teamLogo/CSK.png";
import CSK_bw from "../assets/images/teamLogo/CSK-bw.png";
export function getImage(name) {
switch (name) {
case "CSK":
return CSK;
case "CSK_bw":
return CSK_bw;
}
}
so whenever i need image i just import above function with image name.
and second category images i will use as require.

How to import a component or file in React using variables?

I'm building a web app using React that shows the blueprint for the building you select, in an already selected campus.
I have a "Content" component that loads the campus or building map, depending what you chose.
The "BuildingMap" component needs to load a specific blueprint according to what building you selected. It gets the props.building with the name of the building but I don't know how to load a component using that variable.
I have tried import, fetch and require but nothing seems to work.
Please help.
My code looks something like this:
//Content Component
<BuildingMap building={selectedBuilding} campus={selectedCampus} />
//BuildingMap Component
import *MyBlueprint* from (specific folder depending on the campus selected)
class BuildingMap extends React.Component {
render(){
return (
<div className="blueprint" id={this.props.building}>
{*MyBlueprint*}
</div>
)
}
}
Unfortunately, you cannot import/require components dynamically in React environment.
Depending on how many buildings/blueprints there are, it's possible to import them one by one, create component-building map and pick component by building ID.
If there are many/infinite components to load, I would surely pick another method - don't know content of your problem.
import BlueprintA from './BlueprintA'
import BlueprintB from './BlueprintB'
import BlueprintC from './BlueprintC'
// ...
class BuildingMap extends React.Component {
render(){
const C = {
buildingA: BlueprintA,
buildingB: BlueprintB,
buildingC: BlueprintC,
// ...
}[this.props.building]
return (
<div className="blueprint" id={this.props.building}>
<C />
</div>
)
}
}
This question is pretty old but as I was looking for how to solve the same problem let me give my answer. It can be done with dynamic import React.lazy:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
See more details here: https://reactjs.org/docs/code-splitting.html#reactlazy
To add to #Andreyco's answer:
Using a lookup table of string IDs/names to component classes is a typical React idiom. One common use case is a modal manager component that can render multiple different types of modals. For some examples, see Dan Abramov's answer at "How can I render a modal dialog in Redux?" (not Redux-specific), as well as some of the related articles in the React Component Patterns#Modal Dialogs and Redux Techniques#UI sections of my React/Redux links list.
Per #azium's comment: it is definitely possible to use dynamic importing (via require.ensure() or the new import() function) to load chunks at runtime, and you could add the exports from those dynamically imported chunks into a lookup table when they are loaded.

Resources