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

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"

Related

How to dynamically import an object exported from another file?

In my node_modules, I have a folder with an index.js which exports an object which contains a bunch of icon objects.
export { arrow1, arrow2, arrow3 .. }
I want to somehow dynamically import an icon object from another component. I am using Stencil.js, which is similar to React, and I need to use the icon string passed as a prop to dynamically import that particular icon object. How do I do that? The issue is that the import statement must be at the top of the page, but the prop is defined below.
Is there a way to import an exported object without using the import statement?
I tried with fetch() but it wasn't working. It kept returning status not ok.
I don't see point how importing all icons is a performance issue.
Here is small example, but it depends on what format are the imported icons.
import { IconNames } from '../icon/types';
#Component({
tag: 'custom-component'
})
export class CustomComponent {
#Prop() iconName: keyof IconNames;
render() {
const unicodeIcon = String.fromCharCode(parseInt(getIconHexCharCode(this.iconName), 16));
return (
<span>{unicodeIcon}</span>
)
}
}

Using static html/css/jquery landing pages in ReactJS project

so I had an idea of generating various "landing pages" for my project that would use similar elements with different data.
The idea is to essentially to have my react app (create-react-app) load a "container component" and would then display static landing pages.
For example files are...
screenContainer.jsx
pageOne.html
pageTwo.html
Depending on the user's choice I can render pageOne.html or page2.html. These pages are "templates" which work with jquery css, etc.
Is this possible? If so, what is the best approach.
I'm using html-loader now but am stuck at this:
./src/landingPages/serre/assets/js/plugins/jquery/jquery-3.3.1.min.js
Line 2:1: Expected an assignment or function call and instead saw an expression no-unused-expressions
Any ideas?
Thanks!
Here is my current file react screen container component:
require("es6-object-assign/auto");
import React, { Component, Fragment } from "react";
import $ from "jquery";
import Page from "../landingPages/serre/index.html";
var ReactDOMServer = require("react-dom/server");
var HtmlToReactParser = require("html-to-react").Parser;
var htmlDoc = { __html: Page };
class CreatorLandingPageContainer extends Component {
constructor(props) {
super(props);
}
render() {
return <Fragment>HELLO{this.renderPage()}</Fragment>;
}
renderPage() {
var htmlToReactParser = new HtmlToReactParser();
var reactElement = htmlToReactParser.parse(htmlDoc);
return reactElement;
}
}
export default CreatorLandingPageContainer;

Good practice to import images in ReactJS?

I am adding multiple images in my web page by placing each image in same directory that of components (see screenshot) How can I place the image files in another folder and then access them inside my components.
content.js:
import React, { Component } from 'react';
import java from './java.png';
import neural from './neural.png';
import future from './future.gif';
import neuralnet from './neuralnet.jpg';
import dsa from './dsa.png';
import dl from './dl.jpg';
import ml from './ml.jpg';
import python from './python.png';
import ai from './ai.jpg';
<img className="futuregif" src={future} alt="gif" height="240" width="320"></img>
<img className="javacardimg" src={java} alt="Java" height="65" width="65"></img>
<img className="neuralcardimg" src={neural} alt="neural" height="65" width="65"></img>
and so on.. for all other images
Components and image files are getting mixed together is there any other specific way to do it by making a image folder but then what should be the path in src="".
File structure:
To clarify my comment.
Create a directory assets containing all your assets like images.
Then import the right path and load your content like:
import neural from './assets/images/neural.png';
class myComponent extends Component {
render() {
return (<div><img src={neural} alt=""/></div>);
}
}
In my point of view you can create a js file and export const imageName. in const you can specify your image path.
constant.js
import React from 'react';
import java from './java.png';
export const javaImg = java;
Then in your component file you need to import that js file and you can use those const according to your requirement.
Component
import constant from './constant';
class x extends Component {
constructor(props) {
super(props);
console.log(constant.javaImg);
}
}
export default x;
If you are importing images in same component it'll work but the component will become a lengthy and complex looking.
so my suggestion is like this.

Use react without a router component

If I want to make a web application using reactjs that is not a single page.
Should I compile all the react code into a single file and load it on all pages of the application, then use the function that I expose to render the necessary components?
Example of an html file
<div id="Clock" data-react="Clock"></div>
<div id="HelloWorld" data-react="HelloWorld"></div>
example of index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Clock from './Clock';
import HelloWorld from './HelloWorld';
import OtherComponent from './OtherComponent';
const APPS = {
Clock,
HelloWorld,
OtherComponent
};
const MyReactRender = react => {
let component = react.getAttribute('data-react');
let App = APPS[component];
if(App != undefined) {
ReactDOM.render(<App />, document.getElementById(component));
}
}
document.querySelectorAll('[data-react]').forEach(MyReactRender);
I'd see two ways, of increasing quality and difficulty. In both cases, you use good old anchors elements to redirect the page to a url, to which different templates correspond.
Manually check for the existence of divs id's
In this case, each template includes the same javascript bundle that contains everything in the app and a single element with an id corresponding to the specific component. The idea is to check wether or not an element is present in the page, then activate its corresponding react component if it is.
if (document.getElementById('component-root')) {
ReactDOM.render(<Component />, document.getElementById('component-root'));
}
On the up side, it's quite easily implemented. On the down side, the bundle will always get bigger and bigger, and the list of ifs grows each time you add a new "page".
Separate your modules in actual bundles
Different bundle managers exist, but I'd recommend using Webpack to create multiple bundles that contain only specific part of your application. Then, each template contains only the corresponding div element, as well as that specific bundle.
<head><script src="/js/clock.js"></head>
<body><div id="root-clock"></div></body>
<head><script src="/js/otherComponent.js"></head>
<body><div id="root-other-component"></div></body>
How to package multiple bundles with webpack is out of the scope of this answer, but look here.
I've tried making a react application without a router. I used ternary operators to switch from component to component.
// App Component
class App extends Component {
constructor(props) {
super(props)
this.state = {
inClockComponent: true,
inHelloWorldComponent: false,
inOtherComponent: false
}
}
render() {
const {inClockComponent, inHelloWorldComponent, inOtherComponent} = this.state
return (
<div>
{
inClockComponent
? <Clock> : inHelloWorldComponent
? <HelloWorld> : inOtherComponent ? <OtherComponent> :
<div>No Component Here</div>
}
</div>
}
You could pass a function from the App component that would change the display state to each child component of App
Example
// in App Component
showHelloWorldComponent() {
this.setState({
inClockComponent: false,
inHelloWorldComponent: true,
inOtherComponent: false
)}
}
You insert that function onto a button that would navigate to a different component
Example
// in Clock Component
render() {
return (
<div>
<h2>Time is 5:15 P.M.</h2>
<button onClick={this.props.showHelloWorldComponent}>
Go To Hello World
</button>
)
}
It's a messy solution, and I wouldn't suggest using it in a big application, but I hope this answers your question!

React making components out of elements

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 />
...
*/

Categories

Resources