ReactJs: Dynamic component loading passing properties - javascript

I have a library of ReactJS components, as the following code:
components.js
class Comp1 extends Component {
render () {
return (
<div>Component 1 Text: {this.props.text}</div>
);
}
}
class Comp2 extends Component {
render () {
return (
<div>Component 2 Text: {this.props.text}</div>
);
}
}
export components = {
Comp1,
Comp2
}
The main component needs to choose wich one to render based on a passed property:
main.js
import { components } from './components';
class Main extends Component {
getComponent = (name) => {
return components[name];
};
render () {
let comp = this.getComponent(this.props.componentName);
return (
<div>
<comp <=== HOW TO CALL THE GIVEN COMPONENT PASSING ITS PROPERTY
text={'This is component' + this.props.componentName }
/>
</div>
);
}
}
class App extends Component {
render () {
return (
<div>
<Main componentName='Comp1' /> // Or 'Comp2'
</div>
);
}
}
}
I need in the main code to render the component and pass its properties, but I can´t make it work (see the comments on code). A simple {comp} renders the component, but I need to be able to pass its properties accordingly.
What I´ve tried:
{comp text={'This is component' + this.props.componentName}}
<comp text={'This is component' + this.props.componentName}/>
None of them worked.

You component name need to begin with a UpperCase character. so it should look like
import { components } from './components';
class Main extends Component {
getComponent = (name) => {
return components[name];
};
render () {
let Comp = this.getComponent(this.props.componentName);
return (
<div>
<Comp text={'This is component' + this.props.componentName }
/>
</div>
);
}
}
class App extends Component {
render () {
return (
<div>
<Main componentName='Comp1' /> // Or 'Comp2'
</div>
);
}
}
}

Related

React - change props at child1 with callback and pass new value to child2

In my app I have a child component, 'Menu', where a 'select' state is updated by a click event, like so:
Menus.jsx (child):
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import Brewing from './Brewing.jsx';
import { withRouter } from 'react-router-dom';
class Menus extends Component{
constructor (props) {
super(props);
this.state = {
select: '',
isLoading: false,
redirect: false
};
};
(...)
gotoCoffee = (index) => {
this.setState({isLoading:true, select:this.state.coffees[index]})
setTimeout(()=>{
this.setState({isLoading:false,redirect:true})
},5000)
console.log(this.state.coffees[index])
}
renderCoffee = () => {
if (this.state.redirect) {
return (<Redirect to={'/coffee/'+this.state.select} />)
}
}
render(){
const coffees = this.state.coffees;
return (
<div>
<h1 className="title is-1"><font color="#C86428">Menu</font></h1>
<hr/><br/>
{coffees.map((coffee, index) =>
<span key={coffee}>
<div>
{this.state.isLoading && <Brewing/>}
{this.renderCoffee()}
<div onClick={() => this.gotoCoffee(index)}
style={{textDecoration:'underline',cursor:'pointer'}}>
<strong><font color="#C86428">{coffee}</font></strong></div>
<div>
</div>
</div>
</span>)
}
</div>
);
}
}
export default withRouter(Menus);
the above works.
However, let's say I have another child component, 'Coffee', which should inherit this changed state.
I have learned that passing this event change, and state, from child to another child component, is an anti-pattern. Considering the ways of React, data can only flow from top-to-bottom i.e., from parent-to-child.
So have I tried to manage 'select' state from top to bottom, like so:
App.jsx (parent)
class App extends Component {
constructor() {
super();
this.state = {
select: '',
};
this.onSelectChange = this.onSelectChange.bind(this);
};
then I would use a callback here at 'App.jsx', like so:
onSelectChange(newSelect){
this.setState({ select: newSelect });
}
and pass it to 'Menus' component, like so:
<Route exact path='/menus' render={() => (
<Menus
onSelectChange={this.onSelectChange}
/>
)} />
finally, at child 'Menus', I would user event change to change props, which could be passed to other childs etc:
gotoCoffee = (index) => {
this.setState({isLoading:true})
this.props.onSelectChange(index)
setTimeout(()=>{
this.setState({isLoading:false,redirect:true})
},5000)
console.log(this.props.select)
}
but I'm getting console.log(this.props.select) 'undefined'.
what am I missing?
You are only passing onSelectChange method as a prop to Menu component right now, to access this.props.select, you need to pass select as prop to Menu.
<Route exact path='/menus' render={() => (
<Menus
onSelectChange={this.onSelectChange}
select={this.state.select}
/>
)} />
Whenever this.onSelectChange method gets called and state changes in your App.jsx, your Menu component will be rendered. You can use the updated this.props.select in your render method or in any non static method of your Menu component.
class Menu extends Component {
render() {
console.log(this.props.select);
return (
...
);
}
}

How can I wrap React component?

I need to wrap a React node into this function:
export const foo = (WrappedComponent: *) => {
class fooRenderer extends Component<any> {
render() {
const { bar, ...props } = this.props;
if (bar) {
...
}
return <WrappedComponent {...props} />;
}
}
return fooRenderer;
};
I tried the following:
class MyWrappedComponent extends React.Component {
render() {
...
return foo(
<MyComponent
a={a}
b={b}
</MyComponent>
);
}
}
and received the following error:
Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
So essentially I need to render foo(Component_instance).
you can create your react component out of the function
class fooRenderer extends Component{
render(){
return(
<div>Component</div>
)
}
}
after that call the component in your function
export default function wrappedComponent(a, b){
return <fooRenderer a={a} b={b}/>
}
react component at the deep is function if you like to know

React JS - Passing functions for child components

I have an App component and a function 'modalToggled' inside its.
I want to pass the function to multiple child components until I get to the last one, the 'interiores' component.
Like this:
<App> -> <Coluna1> -> <MenuPrincipal> -> <Portfolio> -> <PortfolioMenu> -> <interiores>
App Component, the parent of all components:
import React, { Component } from 'react';
import Coluna1 from './Coluna1'
class App extends Component {
constructor(props) {
super(props)
this.state = {
modalOn: false
}
this.modalToggled = this.modalToggled.bind(this)
}
modalToggled = (on) => {
this.setState({modalOn: on});
}
render() {
return (
<div>
<Coluna1 onModalToggle={this.modalToggled}/>
</div>
)
}
}
export default App;
This is the 'Coluna1' the first child component. I did the same thing in the another ones: 'MenuPrincipal', 'Portfolio', 'PortfolioMenu'
class Coluna1 extends Component {
constructor(props){
super(props)
}
render() {
return (
<div>
<Header />
<MenuPrincipal onModalToggle={this.props.modalToggled} />
</div>
)
}
}
export default Coluna1
Therefore here is the last component interiores, when I click on the button there appears an error message:
TypeError: _this.props.onModalToggle is not a function
import React, { Component } from 'react'
import Modal from 'react-responsive-modal';
class Interiores extends Component {
constructor(props) {
super(props)
this.state = {
open: false
}
}
onOpenModal = () => {
this.setState({ open: true });
this.props.onModalToggle(true);
};
onCloseModal = () => {
this.setState({ open: false });
this.props.onModalToggle(false);
};
render() {
const { open } = this.state;
return (
<div>
<button onClick={this.onOpenModal}>Open modal</button>
<Modal open={open} onClose={this.onCloseModal} center></Modal>
</div>
)
}
}
export default Interiores;
Does anybody know how to solve it? Thank you
It happens, because in App class you pass prop with name onModalToggle:
<Coluna1 onModalToggle={this.modalToggled}/>
But in Coluna1 you receive this props with wrong name, modalToggled:
<MenuPrincipal onModalToggle={this.props.modalToggled} />
Just make the names of props equal. In Coluna1 and other intermediate components pass and receive this props as onModalToggle:
<MenuPrincipal onModalToggle={this.props.onModalToggle} />
This is the problem
modalToggled = (on) => {
this.setState({modalOn: on});
}
Since this is a class function it needs to be defined like
modalToggled(on) {
this.setState({modalOn: on});
}

React-Chat-Widget props not forwarded

I am using the react-chat-widget and trying to call a function in the base class of my application from a custom component rendered by the renderCustomComponent function of the widget.
Here is the code for the base class:
import React, { Component } from 'react';
import { Widget, handleNewUserMessage, addResponseMessage, addUserMessage, renderCustomComponent } from 'react-chat-widget';
import 'react-chat-widget/lib/styles.css';
import Reply from './Reply.js';
class App extends Component {
handleNewUserMessage = (newMessage) => {
renderCustomComponent(Reply, this.correct);
}
correct = () => {
console.log("success");
}
render() {
return (
<div className="App">
<Background />
<Widget
handleNewUserMessage={this.handleNewUserMessage}
/>
</div>
);
}
}
export default App;
And here is the code for the custom component Reply:
import React, { Component } from 'react';
import { Widget, addResponseMessage, renderCustomComponent, addUserMessage } from 'react-chat-widget';
class Reply extends Component {
constructor(props) {
super(props);
}
sendQuickReply = (reply) => {
console.log(this.props); //returns empty object
//this.props.correct(); <-- should be called
};
render() {
return (
<div className="message">
<div key="x" className={"response"}onClick={this.sendQuickReply.bind(this, "xx")}>xx</div>
</div>)
}
}
export default Reply;
According to ReactJS call parent method this should work. However, when I print the this.props object it is empty, although the documentation of the renderCustomComponent method states that the second argument of the component to render are the props that the component needs (in this case the parent class function).
Where have I gone wrong?
The second parameter is considered as props, but it is expected to be an object. you would pass it like
handleNewUserMessage = (newMessage) => {
renderCustomComponent(Reply, {correct: this.correct});
}

How to send this.state from a component to relay root container

I want to change my root query parameter based on the this.state.eventid which is a child component, but I have no clue how to get props to relay root container. I started based on relay-starter-kit.
I have React component that has a dropdown menu, and onSelect it setStates for eventId
renderAttend() {
if (this.props.groups != null && this.state.success != true) {
var events = this.props.events.map(function(event){
var boundSelect = () => {this.setState({eventid:event.nodes[0].id})}
return <MenuItem style={{fontSize:20}}eventKey={event.nodes[0].id} onSelect={boundSelect.bind(this)}>{event.nodes[0].properties.summary} / {event.nodes[0].properties.start}</MenuItem>
},this)
var teams = this.props.groups.map(function(team){
var boundSelect = () => {this.setState({teamid:team.nodes[0].id})}
return <MenuItem style={{fontSize:20}}eventKey={team.nodes[0].id} onSelect={boundSelect.bind(this)}>{team.nodes[0].properties.name}</MenuItem>
},this)
return (
<div>
<ButtonGroup>
<DropdownButton style={{padding:"15px",fontSize:20}}title="Events" id="bg-vertical-dropdown-2">
{events}
</DropdownButton>
<DropdownButton style={{padding:"15px",fontSize:20,marginLeft:"5px"}} title="Groups" id="bg-vertical-dropdown-2">
{teams}
</DropdownButton>
</ButtonGroup>
</div>
)
}
}
I want to use this state to somehow change my root query...
my approute...
import Relay from 'react-relay';
export default class extends Relay.Route {
static paramDefinitions = {
eventId: {required: false}
};
static queries = {
Event : () => Relay.QL`query{eventState(eventId:$eventId)}`,
};
static routeName = 'AppHomeRoute';
}
and my app.js
import 'babel-polyfill';
import App from './components/App';
import AppHomeRoute from './routes/AppHomeRoute';
import React from 'react';
import ReactDOM from 'react-dom';
import Relay from 'react-relay';
ReactDOM.render(
<Relay.RootContainer
Component={App}
route= {new AppHomeRoute}
renderLoading={function() {
return <div style= {{display:"flex",justifyContent:"center",marginTop:"55px"}}> <h1>Loading...</h1></div>;
}}
renderFailure={function(error, retry) {
return (
<div>
<h1>Click Refresh</h1>
</div>
);
}}
/>,
document.getElementById('root')
);
Now I want to this.state.eventid from the react component to update my root query, but I have no idea how to pass data from child component to react root.container. I do not want to use react-router for this :)
p.s. this.props.events were passed to me by an ajax call so they are not saved in relay/graphql data.
For such a case, the better thing to do is to wrap your root query into a story like
{
store {
events(eventId:$eventId)
}
}
So in the root query you only have
export default class extends Route {
static queries = {
app:() => Relay.QL`query { store }`
};
static routeName = "AppRoute";
}
And in the page you create a fragemnt like
let RelayApp = createContainer(SomeComponent, {
initialVariables: {
eventId: null
},
fragments: {
app: () => Relay.QL `
fragment on Store {
id
events(eventId: $eventId) {
pageInfo {
hasNextPage
}
edges {
cursor
node {
name
...
}
}
}
}
`,
},
});
export
default RelayApp;
For the child component, you set the eventId and onChange event handler as props from parent component. And in the parent componet you implement the event handler and call this.props.setVariables({eventId: someVal}) like
// Child Component
export default class Menu extends Component {
render() {
return(
<ul>
<li onClick={() => this.props.selectItem(val)}>{val}</li>
...
</ul>
)
}
}
// Parent Component
class Main extends Component {
_selectItem = (val) => {
this.props.relay.setVariables({eventId: val});
}
render() {
return(
<div>
<Menu selectItem={() => this._selectItem}/>
</div>
)
}
}
let RelayApp = ...
export default Main
Hope this will help.
There is no easy way to solve this. Either use react-router-relay or nest your query like this and use this.props.relay.setVariables()
viewer {
eventState(eventid:$eventid) {
data
}
}

Categories

Resources