How do I make my modal close in x seconds? - javascript

I am using ReactJS and a Bootstrap modal. I can open the modal just fine, but I would like it to close after 3 seconds.
I tried setTimeout as you can see below, but it doesn't close. I gave setTimeout a callback of handleClose, but after console logging, I can see that handleClose is not being called.
Here is the ItemDetailView Component:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Card, CardImg, CardText, CardBody,
CardTitle, CardSubtitle } from 'reactstrap';
import { addToCart } from '../actions/addToCartAction';
import './ItemDetailView.css';
import ItemAddedModal from './ItemAddedModal';
class ItemDetailView extends Component {
constructor(props) {
super(props);
this.state = {
modalOpen: false
}
// this.toggle = this.toggle.bind(this);
};
// toggle() {
// this.setState({
// modalOpen: !this.state.modalOpen
// });
// };
handleOpen = () => {
console.log("Cart Open", this.state.modalOpen);
this.setState({
modalOpen: true
},() => {setTimeout(this.handleClose(), 3000)});
// setTimeout(this.handleClose(), 3000);
};
handleClose = () => {
this.setState({
modalOpen: false
});
console.log('handleClose fired!')
};
addToCartHandler = () => {
this.props.addToCart(this.props.card);
console.log('addToCart++', this.props.quantity);
this.handleOpen()
// this.setState({
// modalOpen: true
// });
};
render() {
if (!this.props.title) {
return null;
}
return (
<div className="detail-view-wrapper">
<Card className="text-center detail-view-card">
{/* <CardImg top width="100%" src={"/" + this.props.img} alt={this.props.title} /> */}
<CardImg className="detail-view-img" top width="100%" src={"/" + this.props.img} alt={this.props.title} />
<CardBody>
<CardTitle className={"card-title"}>{this.props.title}</CardTitle>
<CardSubtitle>${this.props.price}</CardSubtitle>
<CardText>{this.props.description}</CardText>
{/* <SvgIcon className="cart-icon" onClick={() => this.addToCartHandler()} >
<AddShoppingCart />
</SvgIcon> */}
<button className= "add-to-cart-button" onClick={() => this.addToCartHandler()}>Add To Cart</button>
</CardBody>
</Card>
<ItemAddedModal open={this.state.modalOpen} toggle={this.toggle} />
</div>
);
}
}
const mapStateToProps = state => {
if (!state.data.cardData) {
return {
title: null,
img: null,
description: null,
price: null
}
}
const card = state.data.cardData[state.card.id]
return {
card: card,
title: card.title,
id: card.id,
img: card.img,
description: card.description,
price: card.price,
quantity: 0
};
}
export default connect(mapStateToProps, { addToCart })(ItemDetailView);
Here is the ItemAddedModal:
import React from 'react';
import { Modal, ModalHeader } from 'reactstrap';
import './ItemAddedModal.css';
class ItemAddedModal extends React.Component {
render () {
return (
<div>
<Modal className="item-added-modal" isOpen={this.props.open} toggle={this.props.toggle} className={this.props.className}>
<ModalHeader className="item-added-modal-header">
<p className="item-added-modal-p">Item Added To Cart</p>
</ModalHeader>
</Modal>
</div>
)
};
}
export default ItemAddedModal;

To perform an action after a state is set, we need to pass a callback to setState.
this.setState({
modalOpen: true
},()=>{
console.log(this.state.modalOpen);});

Related

Trying to render a Pop up outside of render: React Js

I am trying to bring popup based on clicking of the respective links. Here I could see onClick is being triggered along with the state change But no modal is appearing.
Can some one tell me what is it that I am doing wrong. I am using semantic-ui-react modal for the same puropse
Sandbox: https://codesandbox.io/s/semantic-ui-example-seg91?file=/Modal.js
import React from "react";
import Modal from "./Modal";
class LoaderExampleText extends React.Component {
constructor(props) {
super(props);
this.state = {
isModalOpen: false
};
}
setModal = (e, value) => {
console.log(value);
e.stopPropagation();
this.setState({ isModalOpen: true });
return (
<Modal
modalOpen={this.state.isModalOpen}
handleClose={() => {
this.setState({ isModalOpen: false });
}}
items={value}
/>
);
};
render() {
return (
<>
<a onClick={e => this.setModal(e, "first item")}>Modal A</a>
<a onClick={e => this.setModal(e, "second Item")}>Modal B</a>
</>
);
}
}
export default LoaderExampleText;
import * as React from "react";
import { Modal } from "semantic-ui-react";
class NestedTableViewer extends React.Component {
render() {
return (
<>
<Modal closeIcon={true} open={this.props.modalOpen}>
<Modal.Header>Modal</Modal.Header>
<Modal.Content>
<h1> {this.props.items}</h1>
</Modal.Content>
</Modal>
</>
);
}
}
export default NestedTableViewer;
Save the value into state and move the modal into the render return. All renderable JSX needs to be returned as a single node tree.
import React from "react";
import Modal from "./Modal";
class LoaderExampleText extends React.Component {
constructor(props) {
super(props);
this.state = {
isModalOpen: false,
value: null
};
}
setModal = (e, value) => {
console.log(value);
e.stopPropagation();
this.setState({ isModalOpen: true, value });
};
render() {
return (
<>
<a onClick={e => this.setModal(e, "first item")}>Modal A</a>
<a onClick={e => this.setModal(e, "second Item")}>Modal B</a>
<Modal
modalOpen={this.state.isModalOpen}
handleClose={() => {
this.setState({ isModalOpen: false, value: null });
}}
items={this.state.value}
/>
</>
);
}
}
export default LoaderExampleText;
In setModal is a function , so you cannot do some think like that, but if you want return you must add in render {setModal}.
So in this case :
import React from "react";
import Modal from "./Modal";
class LoaderExampleText extends React.Component {
constructor(props) {
super(props);
this.state = {
isModalOpen: false,
value: ""
};
}
setModal = (e, value) => {
console.log(value);
e.stopPropagation();
this.setState({ isModalOpen: true });
this.setState({ value: value });
};
render() {
return (
<>
<a onClick={e => this.setModal(e, "first item")}>Modal A</a>
<a onClick={e => this.setModal(e, "second Item")}>Modal B</a>
<Modal
modalOpen={this.state.isModalOpen}
handleClose={() => {
this.setState({ isModalOpen: false });
}}
items={this.state.value}
/>
</>
);
}
}
export default LoaderExampleText;
it will work;

ReactJS: TypeError: render is not a function updateContextConsumer

I'm trying to learn the Context API, and what I want to achieve, is showing the button Login and Sign up on the navigation but I had another error that had from another post I read the docs but me reading and not doing visually that how I learned by doing it making mistaking.
The buttons should open up two modal windows one login and sign up form.
Modal.js
import React from 'react';
import ReactDOM from "react-dom";
import Modal from "react-modal";
import ModalContext from '../Forms/ModalContext';
class ModalProvider extends React.Component {
state = {
loginOpened: false,
signupOpened: false
};
openModal = modalType => () => {
if (modalType === "login") {
this.setState({
loginOpened: true,
signupOpened: false
});
} else if (modalType === "signup") {
this.setState({
loginOpened: false,
signupOpened: true
});
}
};
closeModal = modalType => () => {
if (modalType === "login") {
this.setState({
loginOpened: false
});
} else if (modalType === "signup") {
this.setState({
signupOpened: false
});
}
};
render(props) {
return (
<ModalContext.Provider value={{openModal: this.openModal, closeModal: this.closeModal}}>
<Modal isOpen={loginOpened} onRequestClose={this.closeModal("login")}>
<h1>Login</h1>
<button onClick={this.openModal("signup")}>Open Signup</button>
<button onClick={this.closeModal("login")}>Close this modal</button>
</Modal>
<Modal isOpen={signupOpened} onRequestClose={this.closeModal("signup")}>
<h1>Sign Up</h1>
<button onClick={this.openModal("login")}>Open Login</button>
<button onClick={this.closeModal("signup")}>Close this modal</button>
</Modal>
{props.children}
</ModalContext.Provider>
)
}
}
export default ModalProvider
ModalContext.js
I don't know why the person that helped me and explain did a very great job explain to but just want to know why it is just this line of code.
import {createContext} from 'react'
export default createContext()
Navigation.js
import React from 'react';
import { BrowserRouter as Router, Link } from 'react-router-dom';
import Dropdown from "../dropdowns/dropdowns";
import hamburger from "../images/menu.svg"
// This will display the login and sign up buttons
import ModalContext from '../Forms/ModalContext';
class Navigation extends React.Component {
constructor(props) {
super(props);
this.state = {
isExpanded: false
};
}
handleToggle(e) {
e.preventDefault();
this.setState(prevState => ({
isExpanded: !prevState.isExpanded, // negate the previous expanded state
}));
}
render(props) {
const { isExpanded } = this.state;
return (
<Router>
<div className="NavbarContainer main">
<div className="mobilecontainer LeftNav">
<h2 className="BrandName LeftNav mobileboxmenu inline FarRight">Kommonplaces</h2>
<div className="hamburger inlinev" >
<img
onClick={e => this.handleToggle(e)}
alt="menubtn"
src={hamburger}
/>
</div>
</div>
<div className={`NavBar collapsed ${isExpanded ? "is-expanded" : ""}`}>
<div className="col-a">
<Dropdown/>
<li className="RightNav"><Link to="/">Host Your Space</Link></li>
<li className="RightNav"><Link to="/">About Us</Link></li>
<li className="RightNav"><Link to="/">Contact Us</Link></li>
</div>
<div className="col-c">
{ /* 4. call the prop functions in `Navigation` component */ }
<ModalContext.Consumer>
{({openModal, closeModal}) => <button onClick={openModal("login")}>Login</button>}
{({openModal, closeModal}) => <button onClick={openModal('signup')}>Sign Up</button>}
</ModalContext.Consumer>
</div>
</div>
</div>
</Router>
);
}
}
export default Navigation;
So you first created the ModalContext and the context gives you a Provider and a Consumer.
If you want to use the context for a Consumer, there should be a Provider providing it. For that to happen, the Consumer should be a child of the Provider so that it has access to it.
<Provider>
....
...
<Consumer />
...
</Provider>
But in your case, Provider is not a ancestor of the Consumer.
Typically this is how this gets played out.
Navigation.js
import React from "react";
import { BrowserRouter as Router, Link } from "react-router-dom";
import Dropdown from "../dropdowns/dropdowns";
import hamburger from "../images/menu.svg";
// This will display the login and sign up buttons
import ModalContext from "../Forms/ModalContext";
import ModalProvider from "../Forms/ModalProvider";
class Navigation extends React.Component {
constructor(props) {
super(props);
this.state = {
isExpanded: false
};
}
handleToggle(e) {
e.preventDefault();
this.setState(prevState => ({
isExpanded: !prevState.isExpanded // negate the previous expanded state
}));
}
render(props) {
const { isExpanded } = this.state;
return (
<Router>
{/* Modal provider provides the context to all the children */}
<ModalProvider>
<div className="NavbarContainer main">
<div className="mobilecontainer LeftNav">
<h2 className="BrandName LeftNav mobileboxmenu inline FarRight">
Kommonplaces
</h2>
<div className="hamburger inlinev">
<img
onClick={e => this.handleToggle(e)}
alt="menubtn"
src={hamburger}
/>
</div>
</div>
<div
className={`NavBar collapsed ${isExpanded ? "is-expanded" : ""}`}
>
<div className="col-a">
<Dropdown />
<li className="RightNav">
<Link to="/">Host Your Space</Link>
</li>
<li className="RightNav">
<Link to="/">About Us</Link>
</li>
<li className="RightNav">
<Link to="/">Contact Us</Link>
</li>
</div>
<div className="col-c">
{/* 4. call the prop functions in `Navigation` component */}
{/* Consumer has access to context as children as function*/}
<ModalContext.Consumer>
{({openModal, closeModal, loginOpened, signupOpened}) => {
return (
<React.Fragment>
<button onClick={openModal("login")}> Login</button>
<button onClick={openModal("signup")}>Sign Up</button>
<Modal
isOpen={loginOpened}
onRequestClose={closeModal("login")}
>
<h1>Login</h1>
<button onClick={openModal("signup")}>
Open Signup
</button>
<button onClick={closeModal("login")}>
Close this modal
</button>
</Modal>
<Modal
isOpen={signupOpened}
onRequestClose={closeModal("signup")}
>
<h1>Sign Up</h1>
<button onClick={openModal("login")}>
Open Login
</button>
<button onClick={closeModal("signup")}>
Close this modal
</button>
</Modal>
</React.Fragment>
);
}}
</ModalContext.Consumer>
</div>
</div>
</div>
</ModalProvider>
</Router>
);
}
}
export default Navigation;
ModalProvider.js
import React from "react";
import ReactDOM from "react-dom";
import Modal from "react-modal";
import ModalContext from "../Forms/ModalContext";
class ModalProvider extends React.Component {
state = {
loginOpened: false,
signupOpened: false
};
openModal = modalType => () => {
if (modalType === "login") {
this.setState({
loginOpened: true,
signupOpened: false
});
} else if (modalType === "signup") {
this.setState({
loginOpened: false,
signupOpened: true
});
}
};
closeModal = modalType => () => {
if (modalType === "login") {
this.setState({
loginOpened: false
});
} else if (modalType === "signup") {
this.setState({
signupOpened: false
});
}
};
render(props) {
return (
<ModalContext.Provider
value={{
openModal: this.openModal,
closeModal: this.closeModal,
signupOpened: this.state.signupOpened,
loginOpened: this.state.loginOpened,
}}
>
{props.children}
</ModalContext.Provider>
);
}
}
export default ModalProvider;
I was writing an example app as well so will post it as an answer:
function ToggleModal({ checked, onChange, modalId }) {
console.log('rendering:', modalId);
return (
<label>
{modalId}
<input
type="checkbox"
checked={checked}
onChange={onChange}
/>
</label>
);
}
const ToggleModalContainer = ({ modalId }) => {
const { modals, changeModal } = React.useContext(State);
const checked = modals[modalId];
return React.useMemo(
() =>
ToggleModal({
checked,
modalId,
onChange: () => changeModal(modalId, !checked),
}),
[changeModal, checked, modalId]
);
};
function Modals() {
const state = React.useContext(State);
return Object.entries(state.modals).map(
([key, value]) =>
value && <div key={key}>this is modal {key}</div>
);
}
const State = React.createContext();
const App = () => {
const [modals, setModals] = React.useState({
a: false,
b: false,
c: false,
});
const changeModal = React.useCallback(
(modalId, open) =>
setModals(modals => ({ ...modals, [modalId]: open })),
[]
);
const state = React.useMemo(
() => ({
modals,
changeModal,
}),
[changeModal, modals]
);
return (
<State.Provider value={state}>
<React.Fragment>
{Object.keys(modals).map(modalId => (
<ToggleModalContainer
modalId={modalId}
key={modalId}
/>
))}
<Modals />
</React.Fragment>
</State.Provider>
);
};
//render app
ReactDOM.render(
<App />,
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>

How to pass my onSucceeded() function to the parent component?

I have 2 components OptinPage (parent) and TermsOfServices (child). Optin Page is only used for rendering the TermsOfServices component, which can be reused elsewhere in the application. I want to use my onSucceeded () function from my child component to my parent component. I don't see how to do it at all. Currently the result is such that when I click on the button that validates the TermsOfServices it seems to be an infinite loop, it goes on and on without closing my popup. Before I split my TermsOfServices component into a reusable component it worked fine. Before, all content was gathered in OptinPage. Any ideas? Thanks in advance
my TermsOfServices component:
import API from 'api';
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import {
Block,
BlockTitle,
Col,
Fab,
Icon,
Preloader,
} from 'framework7-react';
import { FormattedMessage } from 'react-intl';
import { connect } from 'react-refetch';
import ReactHtmlParser from 'react-html-parser';
class TermsOfServices extends PureComponent {
static propTypes = {
agreeTosFunc: PropTypes.func.isRequired,
agreeTos: PropTypes.object,
onSucceeded: PropTypes.func,
tos: PropTypes.object.isRequired,
};
static contextTypes = {
apiURL: PropTypes.string,
loginToken: PropTypes.string,
userId: PropTypes.string,
};
static defaultProps = {
agreeTos: {},
onSucceeded: () => {},
};
state = {
currentTos: -1,
};
componentDidUpdate(prevProps) {
const {
agreeTos,
onSucceeded,
tos,
} = this.props;
const { currentTos } = this.state;
/* Prepare for first tos after receiving all of them */
if (
prevProps.tos.pending &&
tos.fulfilled &&
tos.value.length &&
currentTos < 0
) {
this.setState({ currentTos: 0 });
}
/* When sending ToS agreement is done */
if (
prevProps.agreeTos.pending &&
agreeTos.fulfilled
) {
onSucceeded();
}
}
handleNext = () => {
const { agreeTosFunc, tos } = this.props;
const { currentTos: currentTosId } = this.state;
const termsOfServices = tos.value;
const done = currentTosId + 1 === termsOfServices.length;
this.setState({ currentTos: currentTosId + 1 });
if (done) {
agreeTosFunc(termsOfServices.map((v) => v._id));
}
};
render() {
const { tos } = this.props;
const { currentTos: currentTosId } = this.state;
const termsOfServices = tos.value;
const currentTermsOfServices = termsOfServices && termsOfServices[currentTosId];
const loaded = termsOfServices && !tos.pending && tos.fulfilled;
const htmlTransformCallback = (node) => {
if (node.type === 'tag' && node.name === 'a') {
// eslint-disable-next-line no-param-reassign
node.attribs.class = 'external';
}
return undefined;
};
return (
<div>
{ (!loaded || !currentTermsOfServices) && (
<div id="
optin_page_content" className="text-align-center">
<Block className="row align-items-stretch text-align-center">
<Col><Preloader size={50} /></Col>
</Block>
</div>
)}
{ loaded && currentTermsOfServices && (
<div id="optin_page_content" className="text-align-center">
<h1>
<FormattedMessage id="press_yui_tos_subtitle" values={{ from: currentTosId + 1, to: termsOfServices.length }} />
</h1>
<BlockTitle>
{ReactHtmlParser(
currentTermsOfServices.title,
{ transform: htmlTransformCallback },
)}
</BlockTitle>
<Block strong inset>
<div className="tos_content">
{ReactHtmlParser(
currentTermsOfServices.html,
{ transform: htmlTransformCallback },
)}
</div>
</Block>
<Fab position="right-bottom" slot="fixed" color="pink" onClick={() => this.handleNext()}>
{currentTosId + 1 === termsOfServices.length &&
<Icon ios="f7:check" aurora="f7:check" md="material:check" />}
{currentTosId !== termsOfServices.length &&
<Icon ios="f7:chevron_right" aurora="f7:chevron_right" md="material:chevron_right" />}
</Fab>
{currentTosId > 0 && (
<Fab position="left-bottom" slot="fixed" color="pink" onClick={() => this.setState({ currentTos: currentTosId - 1 })}>
<Icon ios="f7:chevron_left" aurora="f7:chevron_left" md="material:chevron_left" />
</Fab>
)}
</div>
)}
</div>
);
}
}
export default connect.defaults(new API())((props, context) => {
const { apiURL, userId } = context;
return {
tos: {
url: new URL(`${apiURL}/tos?outdated=false&required=true`),
},
agreeTosFunc: (tos) => ({
agreeTos: {
body: JSON.stringify({ optIn: tos }),
context,
force: true,
method: 'PUT',
url: new URL(`${apiURL}/users/${userId}/optin`),
},
}),
};
})(TermsOfServices);
My OptIn Page :
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import {
Link,
NavRight,
Navbar,
Page,
Popup,
} from 'framework7-react';
import { FormattedMessage, intlShape } from 'react-intl';
import './OptInPage.scss';
import TermsOfServices from '../components/TermsOfServices';
class OptinPage extends PureComponent {
static propTypes = {
logout: PropTypes.func.isRequired,
opened: PropTypes.bool.isRequired,
};
static contextTypes = {
intl: intlShape,
logout: PropTypes.func,
};
render() {
const { opened, logout } = this.props;
const { intl } = this.context;
const { formatMessage } = intl;
return (
<Popup opened={opened} className="demo-popup-swipe" tabletFullscreen>
<Page id="optin_page">
<Navbar title={formatMessage({ id: 'press_yui_tos_title' })}>
<NavRight>
<Link onClick={() => logout()}>
<FormattedMessage id="press_yui_comments_popup_edit_close" />
</Link>
</NavRight>
</Navbar>
</Page>
<TermsOfServices onSucceeded={this.onSuceeded} />
</Popup>
);
}
}
export default OptinPage;
Just add the data you want the parent to be supplied with in the child component (when it is hit) and then handle the data passed to the parent in the function that you pass in onSuccess.
This will roughly look like this:
const {useState, useEffect} = React;
function App(){
return <Child onSuccess={(data)=>{console.log(data)}}/>;
}
function Child({onSuccess}){
return <div>
<button
onClick={()=>onSuccess("this is the data from the child component")}>
Click to pass data to parent
</button>
</div>;
}
ReactDOM.render(<App/>,document.getElementById('app'));
#element {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id='app'></div>
<div id="element">
<div>node 1</div>
<div>node 2</div>
</div>
to access to parent method or attribute you should use super,
for call to the parent constructor
super([arguments]);
for call parent method
super.parentMethod(arguments);
I recommend create a method on child class and then call the parent method, not directly
for more information take a look on this
https://www.w3schools.com/jsref/jsref_class_super.asp

How to hide some component based on some flag in react js

I want to hide some component based on some flag in react js.
I have an App component where I have Login and other components, I want to hide the other component until Login components this.state.success is false and on click of a button I am changing the sate, but it's not working, I am new to react,
My App Class compoenent -
import React, { Component } from "react";
import logo from "../../logo.svg";
// import Game from "../Game/Game";
import Table from "../Table/Table";
import Form from "../Table/Form";
import Clock from "../Clock/Clock";
import "./App.css";
import Login from "../Login/Login";
class App extends Component {
state = {
success: false
};
removeCharacter = index => {
const { characters } = this.state;
this.setState({
characters: characters.filter((character, i) => {
return i !== index;
})
});
};
handleSubmit = character => {
this.setState({ characters: [...this.state.characters, character] });
};
handleSuccess() {
this.setState({ success: true });
}
render() {
const { characters, success } = this.state;
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<span className="Span-inline">App</span>
<Clock time={new Date()} />
</header>
<Login success={success} handleSuccess={this.handleSuccess} />
{success && (
<div className="container">
<h1>React Tutorial</h1>
<p>Add a character with a name and a job to the table.</p>
<Table
characterData={characters}
removeCharacter={this.removeCharacter}
/>
<h3>Add New character</h3>
<Form handleSubmit={this.handleSubmit} />
</div>
)}
{/* <Game /> */}
</div>
);
}
}
export default App;
My Login component -
import React, { Component } from "react";
import Greeting from "./Greeting";
import LogoutButton from "./LogoutButton";
import LoginButton from "./LoginButton";
class Login extends Component {
constructor(props) {
super(props);
this.handleLoginClick = this.handleLoginClick.bind(this);
this.handleLogoutClick = this.handleLogoutClick.bind(this);
this.state = {
isLoggedIn: false,
name: "",
success: false
};
}
handleLoginClick() {
this.setState({ isLoggedIn: true });
this.setState({ success: true });
}
handleLogoutClick() {
this.setState({ isLoggedIn: false });
this.setState({ success: false });
}
onChange = e => {
this.setState({
name: e.target.value
});
};
render() {
const isLoggedIn = this.state.isLoggedIn;
const name = this.state.name;
// const successLogin = this.state.success;
let button;
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting
isLoggedIn={isLoggedIn}
name={name}
onChange={this.onChange}
/>
{button}
</div>
);
}
}
export default Login;
please guide me on what I am doing wrong.
Why sometime debuggers do not trigger in react component?
For the sake of example I have used functional stateless component here. You can use Class component all upto you.
const conditionalComponent = (props) => {
let condition = true;
return (
{condition && <div><h1>Hello world</h1></div>}
}
Instead of directly giving condition you can even call function which returns a boolean value.
handleLoginClick() {
this.setState({ isLoggedIn: true });
this.setState({ success: true });
this.props.handleSuccess()
}
do like this
<Login success={success} handleSuccess=
{this.handleSuccess} />
bind this function

How to avoid rerendering element in the array in react?

I have a array and I want to render the this array into a few redux forms. I found out that all the forms are rerendered. the code looks like the following:
Form.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link, Events, scrollSpy } from 'react-scroll';
import styles from './Form.css';
import MultipleForm from './MultipleForm';
class Form extends Component {
constructor(props) {
super(props);
const {
workflows,
} = this.props;
this.state = {
curTab: workflows.length > 0 ? workflows[0] : '',
curForm: '',
};
}
componentDidMount() {
Events.scrollEvent.register('begin');
Events.scrollEvent.register('end');
scrollSpy.update();
}
componentWillReceiveProps(nextProps) {
const {
workflows,
} = nextProps;
if (workflows && workflows.length > this.props.workflows) {
this.setState({
curTab: workflows[0],
});
}
}
componentWillUnmount() {
Events.scrollEvent.remove('begin');
Events.scrollEvent.remove('end');
}
handleChangeTab = (value) => {
this.setState({
curTab: value,
});
}
handleActiveTab = (workflow) => {
console.log(workflow);
}
render() {
const {
workflows,
schemaNames,
...rest
} = this.props;
return (
<div className={styles.container}>
<header>
<PerspectiveBar
value={this.state.curTab}
onChange={this.handleChangeTab}
style={{
position: 'fixed',
left: '0',
top: '48px',
width: '100vw',
zIndex: '1380',
}}
>
{workflows.map(wf => (
<PerspectiveTab
key={wf}
label={wf}
value={wf}
onActive={() => this.handleActiveTab(wf)}
/>
))}
</PerspectiveBar>
</header>
<div className={styles.formContainer}>
<Paper className={styles.paperContainer}>
<MultipleForm
workflow={this.state.curTab}
schemaNames={schemaNames}
{...rest}
/>
</Paper>
</div>
<Drawer className={styles.drawer} containerStyle={{ height: 'calc(100% - 104px)', top: '104px' }}>
<div className={styles.drawerContainer}>
{schemaNames.map(schemaName => (
<Link
onSetActive={(to) => {
this.setState({
curForm: to,
});
}}
to={schemaName}
duration={500}
offset={-104}
spy
smooth
>
<MenuItem
checked={this.state.curForm === schemaName}
>
{schemaName}
</MenuItem>
</Link>
))}
</div>
</Drawer>
</div>
);
}
}
Form.propTypes = {
schemaNames: PropTypes.arrayOf(PropTypes.string),
workflows: PropTypes.arrayOf(PropTypes.string),
fetchSchemaNames: PropTypes.func.isRequired,
};
Form.defaultProps = {
schemaNames: [],
workflows: [],
};
export default Form;
MultipleForm.jsx
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import FlatButton from 'material-ui/FlatButton';
import { Element } from 'react-scroll';
import SchemaForm from './SchemaForm';
class MultipleForm extends Component {
componentDidMount() {
console.log('MultipleForm Mounted');
const {
workflow,
fetchSchemaNames,
} = this.props;
if (workflow) fetchSchemaNames(workflow);
}
componentWillReceiveProps(nextProps) {
const {
workflow,
fetchSchemaNames,
} = nextProps;
if (workflow && this.props.workflow !== workflow) fetchSchemaNames(workflow);
}
componentDidUpdate() {
const {
schemaNames,
schemas,
initialValues,
fetchSchemas,
fetchInitialValues,
} = this.props;
const schemasNeedToFetch = this.remainingSchemas(schemaNames, schemas);
if (schemasNeedToFetch.length !== 0) fetchSchemas(schemasNeedToFetch);
const initialValuesNeedToFetch = this.remainingInitialValues(schemaNames, initialValues);
if (initialValuesNeedToFetch.lenght !== 0) fetchInitialValues(initialValuesNeedToFetch, 1);
}
remainingSchemas = (schemaNames, schemas) =>
schemaNames.filter(schemaName => schemaName in schemas === false).sort();
remainingInitialValues = (schemaNames, initialValues) =>
schemaNames.filter(schemaName => schemaName in initialValues === false).sort();
handleSubmitAll = (event) => {
event.preventDefault();
const {
submit,
schemas,
schemaNames,
} = this.props;
schemaNames
.map(schemaName => schemas[schemaName].title)
.forEach((title) => {
submit(title);
});
}
render() {
const {
schemaNames,
schemas,
initialValues,
postForm,
} = this.props;
schemaNames.sort((a, b) => a.localeCompare(b));
return (
<div>
{schemaNames.map(schemaName => (
<Element name={schemaName}>
<SchemaForm
key={schemaName}
schema={schemas[schemaName]}
initialValue={initialValues[schemaName]}
schemaName={schemaName}
postForm={postForm}
/>
</Element>
))}
<div>
<FlatButton
label="Submit"
/>
<FlatButton label="Deploy" />
</div>
</div>);
}
}
MultipleForm.propTypes = {
workflow: PropTypes.string.isRequired,
submit: PropTypes.func.isRequired,
fetchSchemaNames: PropTypes.func.isRequired,
schemas: PropTypes.object,
schemaNames: PropTypes.arrayOf(PropTypes.string),
initialValues: PropTypes.object,
fetchSchemas: PropTypes.func.isRequired,
fetchInitialValues: PropTypes.func.isRequired,
postForm: PropTypes.func.isRequired,
};
MultipleForm.defaultProps = {
schemaNames: [],
};
export default MultipleForm;
SchemaForm
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Liform from 'liform-react';
import theme from './NokiaTheme';
import styles from './Form.css';
class SchemaForm extends Component {
componentDidMount() {
console.log('schema mounted');
}
shouldComponentUpdate() {
return false;
}
handleSubmit = (value) => {
const {
postForm,
schemaName,
} = this.props;
postForm(value, schemaName, 1);
}
render() {
const {
schema,
initialValue,
} = this.props;
console.log('props', this.props);
return (
<div>
<h3 id={schema.$id} className={styles.formTitle}>
{schema.title}
</h3>
<Liform
schema={schema}
onSubmit={value => this.handleSubmit(value)}
destroyOnUnmount={false}
theme={theme}
initialValues={initialValue}
/>
</div>
);
}
}
SchemaForm.propTypes = {
schema: PropTypes.shape({
$id: PropTypes.string,
}),
initialValue: PropTypes.object,
schemaName: PropTypes.string,
postForm: PropTypes.func.isRequired,
};
SchemaForm.defaultProps = {
schema: {},
initialValue: null,
schemaName: '',
};
export default SchemaForm;
the schemaNames will be changed only by adding or deleting some element. for example: the schemaNames will change from ['A', 'B', 'C'] to ['A', 'B', 'D']. I get the schemaNames from the redux. which I fetch online.
But when I check the ConnectedReduxForm, when I change the schemaNames, the SchemaForm will be unmounted and the react will mount the form again. I have tried with setting the ConnectedReduxForm to be PureComponent. It is not helpful.
Could someone help me with that? I have spent a lot of time of this and nothing helps.
Update: I have found the problem, the reason of it is that for each time that I for each time I update the workflow, I need to fetch the schemaNames from the server. But I still do not know why this happended. Could someone explain that?

Categories