qhapaq qhapaq - 2 months ago 11
React JSX Question

React: Render other blocks

I'm new to reactjs, I'm trying to communicate 2 component and render again one of them.

I have the following:

layout.js

import React from 'react';
...
class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
toolbar: 'none'
};
}

getChildContext() {
let me = this;
return {
changeToolbar: function (newToolbar) {
me.setState({ toolbar: newToolbar })
}
}
}

render() {
const {Search, Nav} = this.props;

return (
<div className="wrap">
<Header Search={Search} />
<Toolbar toolbar={this.state.toolbar} />
<div className="main">
<Nav />
<div className="content">
{this.props.children}
</div>
</div>
</div>
)
}
}

Layout.childContextTypes = {
changeToolbar: React.PropTypes.func
}

export default Layout;


toolbar.js

import React from 'react';
...
import ProductToolbar from '../components/toolbar/productToolbar';
import SalesToolbar from '../components/toolbar/salesToolbar';

class Toolbar extends React.Component {
static propTypes = {
toolbar: React.PropTypes.string.isRequired
};

state = {
toolbar: this.props.toolbar
};

componentWillReceiveProps(next_props) {
this.setState({toolbar: next_props.toolbar})
}

render () {
let bar = <div>{this.state.toolbar} undefined</div>;
switch (this.state.toolbar) {
case 'productToolbar':
bar = ProductToolbar;
break;
case 'salesToolbar':
bar = SalesToolbar;
break;
};

return (
<div className='toolbar show'>
{bar}
</div>
)
}
}

export default Toolbar;


productToolbar.js

import React from 'react';

export default class ProductToolbar extends React.Component {
render() {
return (
<div>
productToolbar
</div>
);
}
};


productPage.js

import React, {Component} from 'react';
...

class ProductPage extends React.Component {
componentDidMount() {
this.context.changeToolbar('productToolbar');
};

render() {
return (
<div>Page</div>
);
}
};

ComisionPage.contextTypes = {
changeToolbar: React.PropTypes.func
}

export default ProductPage;


when desire is loaded productPage.js create a special toolbar with options for Productpage.
I pass the name of the toolbar to render the new view, but it does not, missing or that I'm doing wrong?

another best solution was to pass directly toolbar

productPage.js

import ProductToolbar from '../components/toolbar/productToolbar';
...
componentDidMount() {
this.context.changeToolbar(ProductToolbar);
};


It not works for me

Answer

Just to make sure that you are rendering the element. Can you please change you switch statement to:

switch (this.state.toolbar) {
  case 'productToolbar':
    bar = <ProductToolbar />;
    break;
  case 'salesToolbar':
    bar = <SalesToolbar />;
    break;
};

Also, consider using a store (Redux, AltJs?) instead of context since they can get a bit complex on large apps (...I experienced the pain, until I switch to the 'store' approach)