Dynamically rendering react components - facebook

I'm new to reactjs and I'm having a hell of a time understanding this bug.
I've read this, and it seems like the solution is there but I'm drawing a blank on how to implement this correctly:
https://facebook.github.io/react/docs/jsx-in-depth.html#user-defined-components-must-be-capitalized
I am trying to render components based on classNames of clicked elements. The classNames match to component names. When I click an element it calls a function that sets the state of my app to that elements className. I then render the component based on the new state.
When testing, if I place the component directly into my app (not rendering the component name dynamically), it works just fine. But when i render the component name dynamically react thinks it's a built-in DOM element and doesn't render properly at all.
In this image you can see both components, rendered next to each other:
both components, first directly added, and the second with the name rendered dynamically
here is my app component code that is rendering everything:
import React, { Component } from 'react';
import logo from '../logo.svg';
import '../css/App.css';
import menus from '../menus';
import MainNav from './MainNav';
import Products from './Products';
import Demos from './Demos';
import Industry from './Industry';
import Customers from './Customers';
import Trials from './Trials';
import Contact from './Contact';
import Newsroom from './Newsroom';
import About from './About';
import Home from './Home';
class App extends Component {
constructor() {
super();
this.chooseComponent = this.chooseComponent.bind(this);
this.state = {
allMenus: menus,
componentMenu: menus,
//sets initial component to load, changes on each click to the clicked component
clickedComponent: Home
};
}
chooseComponent(event) {
//save the classname of the menu i click
var clickedComp = event.target.className;
//saves a reference to a json object for later use
var menu = menus[clickedComp];
//adds those two vars to the state
this.setState({
componentMenu: menu,
clickedComponent: clickedComp
});
}
render() {
//saves a var for rendering the currently clicked component
var ActiveComponent = this.state.clickedComponent;
return (
<div className="App">
<MainNav choose={this.chooseComponent}/>
//renders the components directly without issue
<Products menuData={this.state.componentMenu} />
//renders the component dynamically with problems
<ActiveComponent menuData={this.state.componentMenu} />
</div>
);
}
}
export default App;
here is and example of one of my component being rendered in the App that's giving problems:
import React from 'react';
import products from '../products';
import ProductsMenu from './ProductsMenu';
import Platform from './Platform';
import Applications from './Applications';
import ExMachina from './ExMachina';
import ProductsHome from './ProductsHome';
import Submenu from './Submenu';
import menus from '../menus';
class Products extends React.Component {
constructor() {
super();
this.showContent=this.showContent.bind(this);
this.state = {
productsOverview: products,
content: <ProductsHome />
}
}
render(props) {
return (
<div className="content">
{this.state.content}
</div>
);
}
}
export default Products;

Related

How to make Remix work with react material ui icons

I'm working on a POC with remix + react material (as that's what we use in our main app). I've gotten most things working but I can't get icons to work. Any page that has an icon just hangs and remix yells at me.
Lambda :\Users\chanp\git\my-remix-app\server timed out after 5 seconds
Here's my entry.client. I stole this from the semi-official remix + mui app. I updated the hydrate to work with react 18 (hydrateRoot instead of just hydrate)
import { CacheProvider } from "#emotion/react";
import CssBaseline from "#mui/material/CssBaseline";
import { ThemeProvider } from "#mui/material/styles";
import * as React from "react";
import { useState } from "react";
import { hydrate } from "react-dom";
import { RemixBrowser } from "#remix-run/react";
import createEmotionCache from "./createEmotionCache";
import ClientStyleContext from "./styles/ClientStyleContext";
import muiTheme from "./styles/muiTheme";
import { ThemeProvider as EmotionThemeProvider } from "#emotion/react";
import Layout from "./src/components/Layout";
import { hydrateRoot } from "react-dom/client";
const container = document.getElementById("app");
// const root = hydrateRoot(container, <App tab="home" />);
interface ClientCacheProviderProps {
children: React.ReactNode;
}
function ClientCacheProvider({ children }: ClientCacheProviderProps) {
const [cache, setCache] = useState(createEmotionCache());
function reset() {
setCache(createEmotionCache());
}
return (
<ClientStyleContext.Provider value={{ reset }}>
<CacheProvider value={cache}>{children}</CacheProvider>
</ClientStyleContext.Provider>
);
}
hydrateRoot(
document,
<ClientCacheProvider>
<EmotionThemeProvider theme={muiTheme}>
<ThemeProvider theme={muiTheme}>
{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<RemixBrowser />
</ThemeProvider>
</EmotionThemeProvider>
</ClientCacheProvider>,
);
Versions
React v18.2
Remix v1.6
Other verions from package.json
"#emotion/react": "^11.10.0",
"#emotion/styled": "^11.10.0",
"#mui/icons-material": "^5.8.4",
"#mui/lab": "^5.0.0-alpha.93",
"#mui/material": "^5.9.3",
"#mui/styled-engine-sc": "^5.9.3",
"#mui/styles": "^5.9.3",
"#mui/x-date-pickers": "^5.0.0-beta.4",
I'm not sure what else would be pertinent to this question. Just let me know if I need to provide more details.
Doesn't work
import { Sensors } from '#mui/icons-material'
Works
import Sensors from "#mui/icons-material/Sensors";
I also had to add
"#mui/icons-material"
to
serverDependenciesToBundle
in the Remix.config.js
Guessing ESBuild is to blame here. Still learnig the quirks so an edit of this answer as to why would be good. Or maybe a link to a resource to a more generic explanation as to why.

Preload a script in react-native-webview

I am using react-native-webview so i want to load script in this. So as the webview calls it loads my script and show my content everytime.
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';
// ...
class MyWebComponent extends Component {
render() {
return <WebView source={{ uri: 'https://reactnative.dev/' }} />;
}
}
So i want to that i will load a Script in the package react-native-webview so that it will load script once and then show my content according to that. So let me know in which file i can make changes in the package to load some script intially.

Ionic2 - Alternate way to route without using injected component?

I am building a mobile app and I'd like the user to have the ability to set their starting page via a settings-page. The idea is that the user can select a page from a list of options, the setting gets stored to local-storage and later, when the user logs back in, the user is automatically taken to that page first.
I have a page-service which contains a mapping of Id's to page-components. This is what I use to find the page I want to use when I read in my user's saved start-page data.
My issue is that I have developed a cyclic-dependency that I don't think I can break without finding a way to route in Ionic2 that doesn't involve using the injected component. As far as I can tell, the only way routing is achieved in Ionic2 is with the NavController.push(component) or Nav.setRoot(component).
PageService.ts
import {Injectable} from "#angular/core";
import {HomePage} from "../pages/home/home";
import {SettingsPage} from "../pages/settings/settings";
import {CartPage} from "../pages/cart/cart";
#Injectable()
export class PageService {
public pages = [
{
id: "HOME",
component: HomePage
}, {
id: "SETTINGS",
component: SettingsPage
}, {
id: "CART",
component: CartPage
}
];
constructor() {
}
getPageById(id: string) {
return this.pages.find(page => (page.id === id));
}
}
settings.ts:
My SettingsPage component has the PageService injected so that it can get access to get the list of pages. This is where my cyclical dependency occurs. The SettingsPage is injecting PageService which has a reference to SettingsPage in it.
import {Component} from "#angular/core";
import {PageService} from "../../providers/page-service";
import {UserService} from "../../providers/user-service";
#Component({
selector: "page-settings",
templateUrl: "settings.html",
})
export class SettingsPage {
startPages = [];
constructor(private pageService: PageService, private userService: UserService) {
this.startPages = this.pageService.getStartPages();
}
}
settings.html:
Just a simple list with a card to output the selection.
<ion-content padding>
<ion-list>
<ion-card padding>
<ion-card-title>Starting Page</ion-card-title>
<ion-item>
<ion-select [(ngModel)]="userService.activeUser.startPage">
<ion-option *ngFor="let page of startPages" value="{{page.id}}">
{{page.id}}
</ion-option>
</ion-select>
</ion-item>
</ion-card>
</ion-list>
</ion-content>
...and finally, when the app starts up and I want to automatically go to my start page I execute the following:
const startPage = this.pageService.getPageById(this.userService.activeUser.startPage);
this.nav.setRoot(startPage.component);
Updated answer
Use forward ref in the SettingsPage constructor..
constructor(#Inject(forwardRef(() => PageService)) private pageService: PageService) {
this.startPages = this.pageService.getStartPages();
}
Old Answer - not appropriate because angular should be handling the instantiation of services through injection. "new"ing is a bad idea (but it did work).
I changed how the PageService was loaded in the SettingsPage and the cyclical dependency was resolved. I moved the PageService code out of the constructor and put it into the ngAfterViewInit() function. Now the PageService is only instantiated when the view is loaded.
ngAfterViewInit(){
this.pageService = new PageService();
this.startPages = this.pageService.getStartPages();
}

Show multiple pages for large screen sizes in Ionic 3

I'm building a simple app with a side menu and two ion-tab. What I am trying to do is, when the screen wide enough, forget about the tabs and open both pages side by side:
To keep the menu visible if the screen is large enough, I am using:
<ion-split-pane when="lg">
And to hide the Tabs:
TS file: this.showTabs = platform.width() < 992;
And then, in the HTML file, I just add the attribute: *ngIf="showTabs"
Is it possible to load two pages inside an ion-content? Any alternative solution?
Any help would be appreciated!
Ok, I've found a solution for this. I'll post it here in case someone experiences the same problem.
We can create a custom component with:
ionic generate component name-of-component
The components can be embedded within the ionic pages. To use them in a Page, you just have to import the component in the .module.ts of the Page and then use the HTML tag with the selector name of the component, as Ivaro18 mentioned:
<component-name></component-name>
If you want to use lazy loading, you can create a components.module.ts inside the components folder to act as an index of all the custom components. It would look like this:
import { NgModule } from '#angular/core';
import { IonicModule } from 'ionic-angular';
import { Component1 } from './component1/component1';
import { Component2 } from './component2/component2';
import { Component3 } from './component3/component3';
#NgModule({
declarations: [
Component1,
Component2,
Component3
],
imports: [IonicModule],
exports: [
Component1,
Component2,
Component3
]
})
export class ComponentsModule{}
Then, in the Pages, we would import ComponentsModule. That would allow us to lazy load any of the components:
<component-2-selector></component-2-selector>
Hope this helps!

React - Redux, submit a form with data from child components

I have a component which is a form, with a number of child components. What is the best way to consolidate the data from all of the child components, when submitting the form? Below is one idea, is this the correct method? I pass a reference to a function that will update a property of a form upon change in a component. What is best practice? Thanks.
import React from 'react';
import { Component , PropTypes} from 'react';
import { connect } from 'react-redux';
import { saveData } from '../actions/index'
import {bindActionCreators} from 'redux';
export default class MyClass extends Component {
constructor(props) {
super (props);
this.formData = {};
this.setFormData = this.setFormData.bind(this);
this.onSubmitHandler = this.onSubmitHandler.bind(this);
}
setFormData(key, value){
this.formData[key] = value;
}
onSubmitHandler(evt){
this.props.saveData(this.formData);
}
render (){
return (
<div>
<form onSubmit = {this.onSubmitHandler} >
<div >
<NameComponent setFormData = {this.setFormData}/>
<AddressComponent setFormData = {this.setFormData}/>
//...lots more components
</form>
</div>
);
}
}
export default connect( mapStateToProps, {saveData)(MyClass)
Yes, this approach is correct, because children are generally expected to delegate to parent that is responsible for them. In fact, that's how Redux Form works. <Field /> input components delegate their state to a Higher Order <Form /> wrapper.
The problem with your approach is that you have to do a lot of repetitive stuff on your own (such as calling onChange, delegating the value etc).
We use Redux Form for one of our projects and it's great as it integrates forms, react and redux. I find myself writing much less code and there is build in validation for both remote, local submission, submission from child components and other neat stuff.
My suggestion is to go with Redux Form instead of reinventing the wheel.