Show/Hide components in ReactJS - reactjs

We have been experiencing some problems in using react now but it kinda boils to one part of how we have been using react.
How should we have been showing/hiding child components?
This is how we have coded it (this are only snippets of our components)...
_click: function() {
if ($('#add-here').is(':empty'))
React.render(<Child />, $('#add-here')[0]);
else
React.unmountComponentAtNode($('#add-here')[0]);
},
render: function() {
return(
<div>
<div onClick={this._click}>Parent - click me to add child</div>
<div id="add-here"></div>
</div>
)
}
and lately I've been reading examples like it should've been somewhere along this lines:
getInitialState: function () {
return { showChild: false };
},
_click: function() {
this.setState({showChild: !this.state.showChild});
},
render: function() {
return(
<div>
<div onClick={this._click}>Parent - click me to add child</div>
{this.state.showChild ? <Child /> : null}
</div>
)
}
Should I have been using that React.render()? It seems to stop various things like shouldComponentUpdate to cascade to child and things like e.stopPropagation...

I've provided a working example that follows your second approach. Updating the component's state is the preferred way to show/hide children.
Given you have this container:
<div id="container">
</div>
you can either use modern Javascript (ES6, first example) or classic JavaScript (ES5, second example) to implement the component logic:
Show/hide components using ES6
Try this demo live on JSFiddle
class Child extends React.Component {
render() {
return (<div>I'm the child</div>);
}
}
class ShowHide extends React.Component {
constructor() {
super();
this.state = {
childVisible: false
}
}
render() {
return (
<div>
<div onClick={() => this.onClick()}>
Parent - click me to show/hide my child
</div>
{
this.state.childVisible
? <Child />
: null
}
</div>
)
}
onClick() {
this.setState(prevState => ({ childVisible: !prevState.childVisible }));
}
};
React.render(<ShowHide />, document.getElementById('container'));
Show/hide components using ES5
Try this demo live on JSFiddle
var Child = React.createClass({
render: function() {
return (<div>I'm the child</div>);
}
});
var ShowHide = React.createClass({
getInitialState: function () {
return { childVisible: false };
},
render: function() {
return (
<div>
<div onClick={this.onClick}>
Parent - click me to show/hide my child
</div>
{
this.state.childVisible
? <Child />
: null
}
</div>
)
},
onClick: function() {
this.setState({childVisible: !this.state.childVisible});
}
});
React.render(<ShowHide />, document.body);

/* eslint-disable jsx-a11y/img-has-alt,class-methods-use-this */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import todoStyle from 'src/style/todo-style.scss';
import { Router, Route, hashHistory as history } from 'react-router';
import Myaccount from 'src/components/myaccount.jsx';
export default class Headermenu extends Component {
constructor(){
super();
// Initial state
this.state = { open: false };
}
toggle() {
this.setState({
open: !this.state.open
});
}
componentdidMount() {
this.menuclickevent = this.menuclickevent.bind(this);
this.collapse = this.collapse.bind(this);
this.myaccount = this.myaccount.bind(this);
this.logout = this.logout.bind(this);
}
render() {
return (
<div>
<div style={{ textAlign: 'center', marginTop: '10px' }} id="menudiv" onBlur={this.collapse}>
<button onClick={this.toggle.bind(this)} > Menu </button>
<div id="demo" className={"collapse" + (this.state.open ? ' in' : '')}>
<label className="menu_items" onClick={this.myaccount}>MyAccount</label>
<div onClick={this.logout}>
Logout
</div>
</div>
</div>
</div>
);
}
menuclickevent() {
const listmenu = document.getElementById('listmenu');
listmenu.style.display = 'block';
}
logout() {
console.log('Logout');
}
myaccount() {
history.push('/myaccount');
window.location.reload();
}
}

Related

How to update the Child component state on Updating the Parent Component state

I have two components 1) Accordion Component and 2) MyCustom Component
Now I am importing Accordion Component into MyCustom Component as Below
import { Accordion } from '../../../controls/accordion';
public clickEvent = () =>{
this.setState({
attachmentsAccordionCollapsed:!this.state.attachmentsAccordionCollapsed
});}
<Accordion title="Attachments" defaultCollapsed={this.state.attachmentsAccordionCollapsed} className={styles.itemCell} ></Accordion>
Now I am changing the state attachmentsAccordionCollapsed value on change event in the MyCustom Component but the property "defaultCollapsed" value of Accordion component does not change or update on changing the state of the MyCustom component.
Accordion Component
import * as React from 'react';
import styles from './Accordion.module.scss';
import { IAccordionProps, IAccordionState } from './index';
import { css } from "#uifabric/utilities/lib/css";
import { DefaultButton, IIconProps } from 'office-ui-fabric-react';
/**
* Icon styles. Feel free to change them
*/
const collapsedIcon: IIconProps = { iconName: 'ChevronRight', className: styles.accordionChevron };
const expandedIcon: IIconProps = { iconName: 'ChevronDown', className: styles.accordionChevron };
export class Accordion extends React.Component<IAccordionProps, IAccordionState> {
private _drawerDiv: HTMLDivElement = undefined;
constructor(props: IAccordionProps) {
super(props);
this.state = {
expanded: props.defaultCollapsed == null ? false : !props.defaultCollapsed
};
}
public componentDidUpdate(prevProps) {
this.state = {
expanded: this.props.defaultCollapsed == null ? false : !this.props.defaultCollapsed
};
}
public render(): React.ReactElement<IAccordionProps> {
return (
<div className={css(styles.accordion, this.props.className)}>
<DefaultButton
toggle
checked={this.state.expanded}
text={this.props.title}
iconProps={this.state.expanded ? expandedIcon : collapsedIcon}
onClick={() => {
this.setState({
expanded: !this.state.expanded
});
}}
aria-expanded={this.state.expanded}
aria-controls={this._drawerDiv && this._drawerDiv.id}
/>
{this.state.expanded &&
<div className={styles.drawer} ref={(el) => { this._drawerDiv = el; }}>
{this.props.children}
</div>
}
</div>
);
}
}
Instead of copying props.defaultCollapsed to negated props.expanded I would suggest not having local state in the accordion and just pass the toggle function to expand from parent like any other controlled component:
class Accordion extends React.Component {
render() {
return (
<div>
Is expanded: {String(this.props.expanded)}
<button onClick={this.props.toggleExpanded}>
toggle expanded
</button>
</div>
);
}
}
class Parent extends React.PureComponent {
state = {
expanded: true,
};
toggleExpanded = () => {
this.setState({ expanded: !this.state.expanded });
};
render() {
return (
<div>
<button onClick={this.toggleExpanded}>
toggle from parent
</button>
<Accordion
expanded={this.state.expanded}
toggleExpanded={this.toggleExpanded}
/>
</div>
);
}
}
ReactDOM.render(
<Parent />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

React Re-Render Component on props Change

I have a Tabbar in my Tabbar Component, Which I Change the index props in it :
class Tabbar extends Component {
state = {
index: this.props.index,
name: this.props.name,
image: this.props.image
};
changeTabs = () => {
this.setState({index: this.props.index});
}
render() {
return (
<React.Fragment>
<div id={this.state.index} className="col">
<button onClick={this.changeTabs}></button>
</div>
</React.Fragment>
);
}
}
export default Tabbar;
And Then In my Other Component, I Wanna Re-Render a fragment after props change. Here's my Code :
import Tabbar from './Tabbar';
class Tabview extends Component {
constructor(props) {
super(props);
this.state = {
tabs: [
{index: 0, name: "tab0", image:require('../Assets/profile.svg'),childView: {ProfilePage} },
{index: 1, name: "tab1", image:require('../Assets/home.svg'),childView: {HomePage}},
{index: 2, name: "tab2", image:require('../Assets/blog.svg'),childView: {BlogPage}},
],
}
}
handleRender = () => {
this.state.tabs.map(item => {
if (item.index === this.props.index) {
return <item.childView/>;
}
})
return <BlogPage/>;
}
render() {
return (
<div>
<Header/>
{this.handleRender()}
{this.state.tabs.map(item =>
<Tabbar key={item.index} index={item.index} name={item.name} image={item.image}/>
)}
</div>
);
}
}
export default Tabview;
The Method "handleRender" should handle the rendering.
I tried to use "componentDidMount" or "componentDidUpdate", But I didn't work.
How Can I Make it Work?
Thank you in advance!
You dont need to have a state in the child component for this reason
You can simply have a callback in parent and call it in child component like below.
import React, { Component } from "react";
class Tabbar extends Component {
render() {
return (
<React.Fragment>
<div id={this.props.index} className="col">
<button
onClick={() => this.props.changeTabs(this.props.index)}
></button>
</div>
</React.Fragment>
);
}
}
export default Tabbar;
And in parent you maintain the active index state
import Tabbar from "./Tabbar";
import React, { Component } from "react";
class Tabview extends Component {
constructor(props) {
super(props);
this.state = {
tabs: [
//your tabs
],
activeIndex: 0
};
}
handleRender = () => {
this.state.tabs.map((item) => {
if (item.index === this.state.activeIndex) {
return <item.childView />;
}
});
return <div />;
};
render() {
return (
<div>
{this.handleRender()}
{this.state.tabs.map((item) => (
<Tabbar
key={item.index}
index={item.index}
name={item.name}
image={item.image}
changeTabs={(index) => this.setState({ activeIndex: index })}
/>
))}
</div>
);
}
}
export default Tabview;

Reactjs don't render until variable is ready

I googled and found some relevant answers but they don't seem to be complete. eg. react.js don't render until ajax request finish
One of the answer suggest to put if else in template, and I have the following Loader component doing this:
var LoaderWrapper = function (props) {
return (
<div>
{props.loaded ? props.children :
<div className="margin-fixer">
<div className="sk-spinner sk-spinner-wave">
<div className="sk-rect1"></div>
<div className="sk-rect2"></div>
<div className="sk-rect3"></div>
<div className="sk-rect4"></div>
<div className="sk-rect5"></div>
</div>
</div>}
</div>
)
};
Now if I use this wrapper:
<LoaderWrapper loaded={variable!=null}>
<MyComponent variable={variable}/>
</LoaderWrapper>
In MyComponent:
render () {
const {variable} = this.props;
return (<div>{variable.abc}</div>)
}
Problem is that still complains about variable is null.
Also tried the following, complains about the same thing...
<LoaderWrapper loaded={false}>
<MyComponent variable={variable}/>
</LoaderWrapper>
You must be doing something wrong, the following code still works and is based on your above idea
import React, { Component } from 'react';
import { render } from 'react-dom';
var LoaderWrapper = function (props) {
return (
<div>
{props.loaded ? props.children :
<h2> Loading ... </h2>}
</div>
)
};
class MyComponent extends Component {
render() {
const { variable } = this.props;
return (<div>{variable.abc}</div>)
}
}
class MyApp extends Component {
constructor() {
this.state = { loaded: false };
this.changeLoading();
}
changeLoading() {
setTimeout(() => {
this.setState({
loaded: true
})
}, 2000)
}
render() {
return (
<LoaderWrapper loaded={this.state.loaded}>
<MyComponent variable={{ abc: 'This is news' }} />
</LoaderWrapper>
)
}
}
render(<MyApp />, document.getElementById('root'));
Please see here for working example https://stackblitz.com/edit/react-q6wynn?file=index.js

How can I prevent all of my accodion components being toggled when clicked in React?

I created a custom Accordion component which again consist of two child components called AccordionTitle and AccordionContent:
The AccordionTitle component has a button. When clicked, the AccordionContent part toggles its style from display:none to block and back when clicked again.
AccordionTitle.js
class AccordionTitle extends Component {
constructor() {
super();
this.show = false;
}
toggle() {
this.show = !this.show;
if (this.props.onToggled) this.props.onToggled(this.show);
}
render() {
return (
<div style={this.props.style}>
<Button onClick={e => this.toggle(e)} />
{this.props.children}
</div>
);
}
}
export default AccordionTitle;
AccordionContent.js
class AccordionContent extends Component {
render() {
let style = this.props.style ? this.props.style : {};
style = JSON.parse(JSON.stringify(style));
style.display = this.props.show ? 'block' : 'none';
return (
<div style={style}>
{this.props.children}
</div>
);
}
}
export default AccordionContent;
Also, I use the following parent component:
Accordion.js
class Accordion extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
Accordion.Title = AccordionTitle;
Accordion.Content = AccordionContent;
export default Accordion;
Now, when I use the Accordion component, it's possible that I might need multiple accordions in a row which would look like this:
ProductAccordion.js
import React, { Component } from 'react';
import Accordion from '../Accordion/Accordion';
class ProductAccordion extends Component {
constructor() {
super();
this.state = {
show: false,
};
}
toggled() {
this.setState({
show: !this.state.show,
});
}
render() {
this.productsJsx = [];
const products = this.props.products;
for (let i = 0; i < products.length; i += 1) {
this.productsJsx.push(
<Accordion.Title onToggled={e => this.toggled(e, this)}>
{products[i].name}
<img src="{products[i].imgsrc}" />
</Accordion.Title>,
<Accordion.Content show={this.state.show}>
{products[i].name}<br />
{products[i].grossprice} {products[i].currency}<br />
<hr />
</Accordion.Content>,
);
}
return (
<Accordion style={styles.container}>
{this.productsJsx}
</Accordion>
);
}
}
export default ProductAccordion;
As you can see, I am grabbing the toggled Event from Accordion.Title and I bind it to the prop show of Accordion.Content via the toggled() method.
Now, this works perfectly fine as long as there is just one product, but if there are more of them, clicking on the button will toggle all AccordionContent instances.
How can I change this so that only the content-part which belongs to the title that contains the clicked button will be toggled?
I also have the feeling that the component Accordion should take care of this (rather than ProductAccordion) by allowing Accordion.Title to delegate the toggled event directly to its sibling Accordion.Content. How can I achieve this?
I would suggest storing the index of the open item in state, instead of a boolean. Then in your render, show={this.state.show} would be something like show={this.state.show === i}.
Full example:
import React, { Component } from 'react';
import Accordion from '../Accordion/Accordion';
class ProductAccordion extends Component {
constructor() {
super();
this.state = {
show: null,
};
}
toggled(event, ind) {
const index = this.state.index;
this.setState({ show:ind === index ? null : ind });
}
render() {
this.productsJsx = [];
const products = this.props.products;
for (let i = 0; i < products.length; i += 1) {
this.productsJsx.push(
<Accordion.Title onToggled={e => this.toggled(e, i)}>
{products[i].name}
<img src="{products[i].imgsrc}" />
</Accordion.Title>,
<Accordion.Content show={this.state.show === i}>
{products[i].name}<br />
{products[i].grossprice} {products[i].currency}<br />
<hr />
</Accordion.Content>,
);
}
return (
<Accordion style={styles.container}>
{this.productsJsx}
</Accordion>
);
}
}
export default ProductAccordion;
and this
class AccordionTitle extends Component {
constructor() {
super();
}
render() {
return (
<div style={this.props.style}>
<Button onClick={this.props.onToggled} />
{this.props.children}
</div>
);
}
}
export default AccordionTitle;

Hiding and showing text in React

I'm having troubles wrapping my head around this. I'm trying to show/hide text inside one of my components, but I'm not able to do it. I get I was clicked! message so I know the function is being passed down. What am I missing?
Do I also need to declare a visibility CSS declaration, maybe that's what I'm missing?
SnippetList.jsx
import React, { Component, PropTypes } from 'react'
import { createContainer } from 'meteor/react-meteor-data';
import Snippet from './snippet'
import { Snippets } from '../../../api/collections/snippets.js'
class SnippetList extends React.Component {
constructor(props) {
super(props);
this.state = { visible: false }
this.toggleVisible = this.toggleVisible.bind(this);
}
toggleVisible() {
this.setState( { visible: !this.state.visible } )
console.log('I was clicked');
}
renderSnippets() {
return this.props.snippets.map( (snippet) => (
<Snippet
key={snippet._id}
title={snippet.title}
content={snippet.content}
onClick={this.toggleVisible}
/>
));
}
render() {
const snippets = Snippets.find({}).fetch({});
return (
snippets.length > 0
?
<ul>{this.renderSnippets()}</ul>
:
<p>No Snippets at this time</p>
)
}
}
SnippetList.propTypes = {
snippets: PropTypes.array.isRequired,
}
export default createContainer(() => {
Meteor.subscribe('snippets');
return {
snippets: Snippets.find({}).fetch()
};
}, SnippetList);
Snippet.jsx
import React, { Component, PropTypes } from 'react'
export default class Snippet extends React.Component {
render() {
const visible = this.props.toggleVisible
return (
<article>
<header>
<h1 className='Snippet-title'>{this.props.title}</h1>
</header>
<div className={visible ? 'show' : 'hidden'} onClick={this.props.onClick}>
<p className='Snippet-content'>{this.props.content}</p>
</div>
</article>
)
}
}
Snippet.propTypes = {
title: PropTypes.string.isRequired,
content: PropTypes.string.isRequired
// toggleVisible: PropTypes.func.isRequired
}
the issue is you aren't passing the hide part as a prop.
in Snippet you do const visible = this.props.toggleVisible but... toggleVisible isn't passed to your Snippet component thus its always undefined
return this.props.snippets.map( (snippet) => (
<Snippet
key={snippet._id}
title={snippet.title}
content={snippet.content}
onClick={this.toggleVisible}
/>
));
add toggleVisible... aka change to this.
return this.props.snippets.map( (snippet) => (
<Snippet
key={snippet._id}
title={snippet.title}
content={snippet.content}
toggleVisible={this.state.visible}
onClick={this.toggleVisible}
/>
));
you should probably also bind your renderSnippets this to the class as well... meaning add this to your constructor this.renderSnippets = this.renderSnippets.bind(this);
Now to talk about your code, why are you rendering a <ul> as the parent of a <article> ? the child of a ul should be a <li> I would refactor your components to be more like this.
class SnippetList extends React.Component {
constructor(props) {
super(props);
this.state = { visible: false };
this.toggleVisible = this.toggleVisible.bind(this);
this.renderSnippets = this.renderSnippets.bind(this);
}
toggleVisible() {
this.setState( { visible: !this.state.visible } )
console.log('I was clicked');
}
renderSnippets() {
return this.props.snippets.map( (snippet) => (
<Snippet
key={snippet._id}
title={snippet.title}
content={snippet.content}
toggleVisible={this.state.visible}
onClick={this.toggleVisible}
/>
));
}
render() {
const snippets = Snippets.find({}).fetch({});
return (
snippets.length > 0
? <ul>{this.renderSnippets()}</ul>
: <p>No Snippets at this time</p>
)
}
}
export default class Snippet extends React.Component {
render() {
const {toggleVisible: visible} = this.props;
return (
<li>
<article>
<header>
<h1 className="Snippet-title">{this.props.title}</h1>
</header>
<div onClick={this.props.onClick}>
<p className={visible ? 'show Snippet-content' : 'hidden Snippet-content'}>{this.props.content}</p>
</div>
</article>
</li>
)
}
}

Resources