How can I make the Snackbar work in a class component? - javascript

These are my codes for the snackbar and it wasn't working whenever I'll click the button. I wanted the snackbar to appear once I'll click the button "confirm". Almost all of the examples I have seen are in a functional component, so how can I make the Snackbar work as expected in a class component?
class name extends Component {
constructor() {
super();
this.state = { orders: [], open: false };
}
handleOpen = () => this.setState({ open: true });
handleClose = () => this.setState({ open: false });
columns = [
{
name: "Confirm",
options: {
customBodyRender: (value, tableMeta) => {
return (
<FormControlLabel
value={value}
control={
<Button>
confirm
</Button>
}
onClick={(e) => {
try {
//firestore codes
);
} catch (err) {
console.log(err);
}
this.handleOpen();
}}
/>
);
},
},
},
];
//code for options
//data fetching codes
render() {
const { open } = this.state;
return this.state.orders ? (
<div>
//muidatatable codes
<Snackbar
anchorOrigin={{
vertical: "bottom",
horizontal: "left",
}}
open={open}
onClose={this.handleClose}
autoHideDuration={2000}
// other Snackbar props
>
Order Confirmed
</Snackbar>
</div>
) : (
<p>Loading...</p>
);
}
}

Ignoring a few syntax errors, you should check if there are any orders by using the length and not just by mere existence of the array as you have initialized an empty array this.state.orders will always result in true. Instead use this.state.orders.length > 0 ? to check if there are any orders or not.
Snackbar's child(ren) should be wrapped in components and not just strings directly, for using string directly you can use message prop of Snackbar.
Also, it's a standard to write class's name starting with an upper-case letter.
Here's a working code: Material UI Snackbar using classes
import React, { Component } from "react";
import { FormControlLabel, Button, Snackbar } from "#material-ui/core";
import MuiAlert from "#material-ui/lab/Alert";
export default class Name extends Component {
constructor() {
super();
this.state = { orders: [], open: false };
}
handleOpen = () => this.setState({ open: true });
handleClose = () => this.setState({ open: false });
handleClick = () => this.setState({ orders: [1], open: true });
columns = [
{
name: "Confirm",
options: {
customBodyRender: (value, tableMeta) => {
return (
<FormControlLabel
value={value}
control={<Button>confirm</Button>}
onClick={(e) => {
try {
//firestore codes
} catch (err) {
console.log(err);
}
this.handleOpen();
}}
/>
);
}
}
}
];
//code for options
//data fetching codes
render() {
const { open } = this.state;
return (
<>
<Button variant="outlined" onClick={this.handleClick}>
Open snackbar
</Button>
{this.state.orders.length > 0 ? (
<div>
<Snackbar
anchorOrigin={{
vertical: "bottom",
horizontal: "left"
}}
open={open}
onClose={this.handleClose}
autoHideDuration={2000}
// other Snackbar props
>
{/* <span
style={{
background: "#000",
color: "#fff",
padding: "20px 5px",
width: "100%",
borderRadius: "5px"
}}
>
Order Confirmed
</span> */}
<MuiAlert
onClose={this.handleClose}
severity="success"
elevation={6}
variant="filled"
>
Success Message
</MuiAlert>
</Snackbar>
</div>
) : (
<p>loading...</p>
)}
</>
);
}
}

The following changes are made to make it work:
Removed Order Confirmed and used message prop of Snackbar
Passed values to orders array in constructor
Passed true in open variable.
Below is the working code for snack bar.
import React, { Component } from "react";
import Snackbar from "#material-ui/core/Snackbar";
class SnackBarSof extends Component {
constructor() {
super();
this.state = { orders: [1, 2], open: true };
}
handleOpen = () => this.setState({ open: true });
handleClose = () => this.setState({ open: false });
render() {
console.log(this.state.orders);
console.log(this.state);
const { open } = this.state;
return this.state.orders ? (
<div>
<Snackbar
anchorOrigin={{
vertical: "bottom",
horizontal: "left",
}}
open={open}
onClose={this.handleClose}
message="order confirmed"
autoHideDuration={2000}
></Snackbar>
</div>
) : (
<p>Loading...</p>
);
}
}
export default SnackBarSof;

Related

How to call method inside main Component from outside in Reactjs

I need to call cancelMethod with params from Button onClick inside popover. However I could not access this method. Can you explain is it possible to access. If yes how can I do it?
const popover = (
<Popover id="popover-basic">
<Popover.Title as="h3">Cancel reservation</Popover.Title>
<Popover.Content>
for <strong>canceling</strong> course. Click here:
<Button onClick={cancelMethod()} variant='danger'>Cancel</Button>
</Popover.Content>
</Popover>
);
const Event = ({event}) => (
<OverlayTrigger trigger="click" placement="top" overlay={popover}>
<Button
style={{background:"transparent", border:"none"}}
>{event.title} <br/> Lecture Room:{event.room}<br/> Teacher: {event.instructor}</Button>
</OverlayTrigger>
);
export default class NewCalendarView extends Component {
cancelMethod(id){
alert("Hello"+id);
}
componentDidMount() {
API.getLectures().then((res)=>{
console.log(res)
const cal=res.map((lec)=>{
let lecture= {
instructor: lec.teacherName,
room: lec.room,
title: lec.subject,
startDate : moment(lec.date+"T"+lec.hour).toDate(),
endDate: moment(lec.date+"T"+lec.hour+"-02:00").toDate()
}
return lecture;
})
this.setState({events:cal,loading:null,serverErr:null})
}).catch((err)=>{
this.setState({serverErr:true,loading:null})
})
}
constructor(props) {
super(props);
this.state = {
events: []
}
}
render() {
return (
<div style={{
flex: 1
}}>
{console.log(this.state.events)}
<Calendar
localizer={localizer}
events={this.state.events}
startAccessor='startDate'
endAccessor='endDate'
defaultView='week'
views={['month', 'week', 'day']}
culture='en'
components={{
event: Event
}}
/>
</div>
);
}
}
You can define the functions Popover and Event within the class and the call the function with this keyword.
export default class NewCalendarView extends Component {
cancelMethod(id){
alert("Hello"+id);
}
componentDidMount() {
API.getLectures().then((res)=>{
console.log(res)
const cal=res.map((lec)=>{
let lecture= {
instructor: lec.teacherName,
room: lec.room,
title: lec.subject,
startDate : moment(lec.date+"T"+lec.hour).toDate(),
endDate: moment(lec.date+"T"+lec.hour+"-02:00").toDate()
}
return lecture;
})
this.setState({events:cal,loading:null,serverErr:null})
}).catch((err)=>{
this.setState({serverErr:true,loading:null})
})
}
constructor(props) {
super(props);
this.state = {
events: []
}
}
Popover = (
<Popover id="popover-basic">
<Popover.Title as="h3">Cancel reservation</Popover.Title>
<Popover.Content>
for <strong>canceling</strong> course. Click here:
<Button onClick={cancelMethod()} variant='danger'>Cancel</Button>
</Popover.Content>
</Popover>
);
Event = ({event}) => (
<OverlayTrigger trigger="click" placement="top" overlay={this.popover}> // added the this keyword
<Button
style={{background:"transparent", border:"none"}}
>{event.title} <br/> Lecture Room:{event.room}<br/> Teacher: {event.instructor}</Button>
</OverlayTrigger>
);
render() {
return (
<div style={{
flex: 1
}}>
{console.log(this.state.events)}
<Calendar
localizer={localizer}
events={this.state.events}
startAccessor='startDate'
endAccessor='endDate'
defaultView='week'
views={['month', 'week', 'day']}
min={new Date(2020, 1, 0, 7, 0, 0)}
max={new Date(2022, 1, 0, 21, 0, 0)}
culture='en'
components={{
event: this.Event // added the this keyword
}}
/>
</div>
);
}
}
One way would be to pass it as prop to popover (which I renamed to PopoverInstance as Popover was already taken). This unfortunately has a side effect of having to drill the prop two levels down (instead of direct one level down). An alternative approach would be to introduce outside state (like Context or Redux) that manages state and methods. It would certainly help with prop drilling.
If cancelMethod is only used in this popover, you can consider moving it there as well.
Also I am unsure how Calendar works, so take that into consideration when you look at the example I've set below.
const PropoverInstance = ({cancelMethod}) => (
<Popover id="popover-basic">
<Popover.Title as="h3">Cancel reservation</Popover.Title>
<Popover.Content>
for <strong>canceling</strong> course. Click here:
<Button onClick={cancelMethod()} variant='danger'>Cancel</Button>
</Popover.Content>
</Popover>
);
const Event = ({event, cancelMethod}) => (
<OverlayTrigger trigger="click" placement="top" overlay={<PopoverInstance cancelMethod={cancelMethod} />}>
<Button
style={{background:"transparent", border:"none"}}
>{event.title} <br/> Lecture Room:{event.room}<br/> Teacher: {event.instructor}</Button>
</OverlayTrigger>
);
export default class NewCalendarView extends Component {
cancelMethod(id){
alert("Hello"+id);
}
componentDidMount() {
API.getLectures().then((res)=>{
console.log(res)
const cal=res.map((lec)=>{
let lecture= {
instructor: lec.teacherName,
room: lec.room,
title: lec.subject,
startDate : moment(lec.date+"T"+lec.hour).toDate(),
endDate: moment(lec.date+"T"+lec.hour+"-02:00").toDate()
}
return lecture;
})
this.setState({events:cal,loading:null,serverErr:null})
}).catch((err)=>{
this.setState({serverErr:true,loading:null})
})
}
constructor(props) {
super(props);
this.state = {
events: []
}
}
render() {
return (
<div style={{
flex: 1
}}>
{console.log(this.state.events)}
<Calendar
localizer={localizer}
events={this.state.events}
startAccessor='startDate'
endAccessor='endDate'
defaultView='week'
views={['month', 'week', 'day']}
culture='en'
components={{
event: <Event event={???} cancelMethod={cancelMethod} />
}}
/>
</div>
);
}
}

Semantic UI modal onOpen/onClose not working

I want to let the modal close itself after 3000ms.
But the onOpen callback is not called at all when the modal is open.
Is there a workaround for this?
I put console.log in onOpen and onClose, but nothing is appearing in the console.
import React, { Component } from 'react'
import { Modal, Button, Header } from 'semantic-ui-react'
export default class YourTurnModal extends Component {
constructor(props) {
super(props)
this.state = {
modalState: this.props.isYourTurn,
}
this.handleOpen = this.handleOpen.bind(this)
this.handleClose = this.handleClose.bind(this)
}
componentWillReceiveProps(nextProps) {
this.setState({ modalState: nextProps.isYourTurn })
}
render() {
return (
<div>
<Modal
onOpen={() => {
console.log("Open", this.state.modalState);
this.setState({
modalState: true
},()=>{
setTimeout(() => {this.setState({ modalState: false });}, 3000);});
}}
open={this.state.modalState}
onClose={() => {this.setState({ modalState: false });console.log("here")}}
>
<Modal.Content style={{ borderless: 'true' }}>
<Header>
Your turn!
</Header>
<Button
color="green"
onClick={() => {this.setState({ modalState: false })}}>
close
</Button>
</Modal.Content>
</Modal>
</div>
)
}
}
I tried with:
<YourTurnModal isYourTurn={true} />

React Bottleneck TextInput Inputfield

I've got a big react app (with Redux) here that has a huge bottleneck.
We have implemented a product search by using product number or product name and this search is extremely laggy.
Problem: If a user types in some characters, those characters are shown in the InputField really retarded. The UI is frozen for a couple of seconds.
In Internet Explorer 11, the search is almost unusable.
It's a Material UI TextField that filters products.
What I already did for optimization:
Replaced things like style={{
maxHeight: 230,
overflowY: 'scroll',
}} with const cssStyle={..}
Changed some critical components from React.Component to React.PureComponent
Added shouldComponentUpdate for our SearchComponent
Removed some unnecessary closure bindings
Removed some unnecessary objects
Removed all console.log()
Added debouncing for the input field (that makes it even worse)
That's how our SearchComponent looks like at the moment:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Downshift from 'downshift';
import TextField from '#material-ui/core/TextField';
import MenuItem from '#material-ui/core/MenuItem';
import Paper from '#material-ui/core/Paper';
import IconTooltip from '../helper/icon-tooltip';
import { translate } from '../../utils/translations';
const propTypes = {
values: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
legend: PropTypes.string,
helpText: PropTypes.string,
onFilter: PropTypes.func.isRequired,
selected: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
isItemAvailable: PropTypes.func,
};
const defaultProps = {
legend: '',
helpText: '',
selected: '',
isItemAvailable: () => true,
};
const mapNullToDefault = selected =>
(selected === null || selected === undefined ? '' : selected);
const mapDefaultToNull = selected => (!selected.length ? null : selected);
class AutoSuggestField extends Component {
shouldComponentUpdate(nextProps) {
return this.props.selected !== nextProps.selected;
}
getLegendNode() {
const { legend, helpText } = this.props;
return (
<legend>
{legend}{' '}
{helpText && helpText.length > 0 ? (
<IconTooltip helpText={helpText} />
) : (
''
)}
</legend>
);
}
handleEvent(event) {
const { onFilter } = this.props;
const value = mapDefaultToNull(event.target.value);
onFilter(value);
}
handleOnSelect(itemId, item) {
const { onFilter } = this.props;
if (item) {
onFilter(item.label);
}
}
render() {
const { values, selected, isItemAvailable } = this.props;
const inputValue = mapNullToDefault(selected);
const paperCSSStyle = {
maxHeight: 230,
overflowY: 'scroll',
};
return (
<div>
<div>{this.getLegendNode()}</div>
<Downshift
inputValue={inputValue}
onSelect={(itemId) => {
const item = values.find(i => i.id === itemId);
this.handleOnSelect(itemId, item);
}}
>
{/* See children-function on https://github.com/downshift-js/downshift#children-function */}
{({
isOpen,
openMenu,
highlightedIndex,
getInputProps,
getMenuProps,
getItemProps,
ref,
}) => (
<div>
<TextField
className="searchFormInputField"
InputProps={{
inputRef: ref,
...getInputProps({
onFocus: () => openMenu(),
onChange: (event) => {
this.handleEvent(event);
},
}),
}}
fullWidth
value={inputValue}
placeholder={translate('filter.autosuggest.default')}
/>
<div {...getMenuProps()}>
{isOpen && values && values.length ? (
<React.Fragment>
<Paper style={paperCSSStyle}>
{values.map((suggestion, index) => {
const isHighlighted = highlightedIndex === index;
const isSelected = false;
return (
<MenuItem
{...getItemProps({ item: suggestion.id })}
key={suggestion.id}
selected={isSelected}
title={suggestion.label}
component="div"
disabled={!isItemAvailable(suggestion)}
style={{
fontWeight: isHighlighted ? 800 : 400,
}}
>
{suggestion.label}
</MenuItem>
);
})}
</Paper>
</React.Fragment>
) : (
''
)}
</div>
</div>
)}
</Downshift>
</div>
);
}
}
AutoSuggestField.propTypes = propTypes;
AutoSuggestField.defaultProps = defaultProps;
export default AutoSuggestField;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.0/umd/react-dom.production.min.js"></script>
It seems, that I did not find the performance problem as it still exists. Can someone help here?

Dynamic content with React js Modal

I want to get dynamic content with React js modal I am using package react-responsive-modal. First I render all the post through map. Now I want when I click the individual post the modal should pop up and show me only that particular post's title and body. Now I can't figure out how to get an individual post in modal.
Is it possible to do that via third-party package or I have to make custom modal for that?
import React from 'react';
import Modal from 'react-responsive-modal';
import Axios from 'axios';
const styles = {
fontFamily: 'sans-serif',
textAlign: 'center'
};
class App extends React.Component {
state = {
posts: [],
open: false
};
componentDidMount() {
let url = 'https://jsonplaceholder.typicode.com/posts';
Axios.get(url).then(res => {
this.setState({
posts: res.data.slice(0, 10)
});
console.log(res.data.slice(0, 10));
});
}
onOpenModal = () => {
this.setState({ open: true });
};
onCloseModal = () => {
this.setState({ open: false });
};
renderPosts() {
return this.state.posts.map(post => {
return (
<div
key={post.id}
style={{ width: 400, height: 400, backgroundColor: 'orange' }}
onClick={this.onOpenModal}
>
<h1>{post.title}</h1>
</div>
);
});
}
renderModal(id, title, body) {
return this.state.posts.map(post => {
return (
<div key={post.id} style={{ width: 400, height: 400, backgroundColor: 'orange' }}>
<h1>{post.id}</h1>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
});
}
render() {
const { open } = this.state;
return (
<div style={styles}>
<h2>react-responsive-modal</h2>
<div>{this.renderPosts()}</div>
<Modal open={open} onClose={this.onCloseModal} center>
<h2>Simple centered modal</h2>
<div>{this.renderModal()}</div>
</Modal>
</div>
);
}
}
export default App;
You'll need to introduce some additional state on your App component that keeps track of the currently selected post. In your onOpenModal() method, you can update that state with the index of the post that was clicked. Then, in renderModal(), you can check what the selected post is and only render that post instead of mapping over the entire array.
class App extends React.Component {
state = {
posts: [],
open: false,
selectedPost: null // Keep track of the selected post
};
componentDidMount() {
let url = "https://jsonplaceholder.typicode.com/posts";
Axios.get(url).then(res => {
this.setState({
posts: res.data.slice(0, 10)
});
console.log(res.data.slice(0, 10));
});
}
onOpenModal = i => {
this.setState({
open: true,
selectedPost: i // When a post is clicked, mark it as selected
});
};
onCloseModal = () => {
this.setState({ open: false });
};
renderPosts = () => {
return this.state.posts.map((post, i) => {
return (
<div
key={post.id}
style={{ width: 400, height: 400, backgroundColor: "orange" }}
onClick={() => this.onOpenModal(i)} // Pass the id of the clicked post
>
<h1>{post.title}</h1>
</div>
);
});
}
renderModal = () => {
// Check to see if there's a selected post. If so, render it.
if (this.state.selectedPost !== null) {
const post = this.state.posts[this.state.selectedPost];
return (
<div
style={{ width: 400, height: 400, backgroundColor: "orange" }}
>
<h1>{post.id}</h1>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
}
render() {
const { open } = this.state;
return (
<div style={styles}>
<h2>react-responsive-modal</h2>
<div>{this.renderPosts()}</div>
<Modal open={open} onClose={this.onCloseModal} center>
<h2>Simple centered modal</h2>
<div>{this.renderModal()}</div>
</Modal>
</div>
);
}
}
In the post onClick function set the post id/index in state along with the open flag
Inside the modal render use the saved index/id to pass that post to the modal as a param/prop.
You dont need to map over all posts inside the modal.
Sample
onOpenModal = (index) => {
this.setState({ open: true, selectedPostIndex: index });
};
onCloseModal = () => {
this.setState({ open: false, selectedPostIndex: undefined })
}
renderPosts() {
return this.state.posts.map((post, index) => {
return (
<div key={post.id} onClick={() => this.onOpenModal(index)}>
<h1>{post.title}</h1>
</div>
)
})
}
render() {
....
<Modal open={open} onClose={this.onCloseModal} center>
<h2>Simple centered modal</h2>
<div>{this.renderModal(this.state.posts[this.state.selectedPostIndex])}</div>
</Modal>
....
}
renderModal(post) {
return (
<div key={post.id} style={{ width: 400, height: 400, backgroundColor: 'orange' }}>
<h1>{post.id}</h1>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
)
}
Using React Hooks
Create a modal with dynamic props like this
export default function Modal({
open,
setOpen,
onConfirm,
title,
description,
confirmText,
})
Then render the component.
i did it like this
const getModal = () => {
return (
<Modal open={open} setOpen={setOpen} title={title} description={description} confirmText={confirmText} onConfirm={confirmAction} />
)
}
and then when you want to display your dynamic modal
use a function like this
ConfirmAction can not be a function you should call the function inside that Modal according to that confirmation
const createModal = (title, description, confirmText, confirmAction) => {
setTitle(title);
setDescription(description);
setConfirmText(confirmText);
setConfirmAction(confirmAction);
setOpen(true);
}
Initialize your state with one array which will hold
state = {
posts: [],
open: false,
modalShow: [false,false,false,false,false,false,false,false,false,false] // this is 10 as you have only 10 posts
};
Now modify render posts
onOpenModal = (id) => {
const newModalShow = [...this.state.modalShow];
newModalShow[id] = true;
this.setState({ modalShow: newModalShow});
};
renderPosts() {
return this.state.posts.map((post,index) => {
return (
<Fragement>
<div
key={post.id}
style={{ width: 400, height: 400, backgroundColor: 'orange' }}
onClick={()=>this.onOpenModal(index)}
>
<h1>{post.title}</h1>
</div>
<Modal open={this.state.modalShow[index]} onClose={this.onCloseModal} center>
<h2>post.title</h2>
<div>{this.renderModal()}</div>
</Modal>
<Fragement>
);
});
}

Add a function into a onClick

I want to use React.js to build a single page application and I want to create a list in a material-ui drawer. I want to add an element into an array every time I press a button but I don't how to write this function.
Here is my buttom:
<RaisedButton
label="Next"
primary={true}
onClick={this.onNext}
/>
Here is onNext function:
onNext = (event) => {
const current = this.state.controlledDate;
const date = current.add(1, 'days');
this.setState({
controlledDate: date
});
this.getImage(moment(date));
}
And this is the code I want to add into onNext function:
menuItems.push(<MenuItem onClick={this.handleClose}>{this.state.image.date}</MenuItem>);
This is a sample code that adds drawer menu items using state
const { RaisedButton, MuiThemeProvider, Drawer, getMuiTheme, MenuItem } = MaterialUI;
class Sample extends React.Component {
state = {
open: false,
items: [],
}
handleClose = () => {
this.setState({ open: false });
}
handleOpen = () => {
this.setState({ open: true })
}
onNext = () => {
this.setState(state => {
return Object.assign({}, state, {
items: state.items.concat([
{
// add any other button props here (date, image, etc.)
text: `Item ${state.items.length + 1}`
}
]),
});
})
}
render() {
return (
<div>
<Drawer
openSecondary={true}
width={200}
open={this.state.open}
>
{this.state.items.map(item => (
<MenuItem onClick={this.handleClose}>{item.text}</MenuItem>
))}
</Drawer>
<RaisedButton
label="Next"
primary={true}
style={{ margin: 12 }}
onClick={this.onNext} />
<RaisedButton
label="Open Drawer"
primary={true}
style={{ margin: 12 }}
onClick={this.handleOpen} />
</div>
);
}
}
const App = () => (
<MuiThemeProvider muiTheme={getMuiTheme()}>
<Sample />
</MuiThemeProvider>
);
ReactDOM.render(
<App />,
document.getElementById('container')
);
Try it here: https://jsfiddle.net/jprogd/eq533rzL/
Hope it should give you an idea how to go further

Categories

Resources