How to use pagination in Reactjs application - javascript

I am implementing pagination for my blog page by using react-js-pagination.
I am unable to fix this pagination ui and its content per page
Bind my data accordingly per page
I have tried to import less from bootstrap but it is not rendering for this.
Any suggestion on this to solve this pagination issue?
Updated code: it is working now
//blog.js
import React, {Component} from 'react';
import {Card, Grid, Cell, Dialog, CardMenu, Button, CardTitle,
CardText, CardActions, FABButton, Icon} from'react-mdl';
import { Container} from 'reactstrap';
import { connect } from 'react-redux';
import { getBlog, deleteBlog } from '../../actions/resumeActions';
import PropTypes from 'prop-types';
import Loading from './Loading';
import Moment from 'moment';
import BlogModal from "./BlogModal";
import Pagination from "react-js-pagination";
class Blogs extends Component{
constructor(props) {
super(props);
this.state = {
modal: false,
justClicked: null,
activePage: 1
};
this.handleOpenDialog = this.handleOpenDialog.bind(this);
this.handleCloseDialog = this.handleCloseDialog.bind(this);
}
static propTypes = {
getContact: PropTypes.func.isRequired,
deleteContact: PropTypes.func.isRequired,
resume: PropTypes.object.isRequired,
isAuthenticated: PropTypes.bool,
auth: PropTypes.object.isRequired,
loading: PropTypes.object.isRequired
}
toggle = () => {
this.setState({
modal: !this.state.modal
});
}
handleOpenDialog(id) {
this.setState({
openDialog: true,
justClicked: id
});
}
handleCloseDialog() {
this.setState({
openDialog: false
});
}
componentDidMount() {
this.props.getBlog();
}
onDeleteBlogClick = (id) => {
this.props.deleteBlog(id);
};
handlePageChange(pageNumber) {
console.log(`active page is ${pageNumber}`);
this.setState({activePage: pageNumber});
}
cardDialog(blogs, user){
return(
<Grid style={{padding: 0, display: 'contents'}}>
{blogs.map(({ _id, blog_name, blog_desc, blog_image_link, blog_by }) => (
<Cell col={12}>
<Dialog open={this.state.openDialog && this.state.justClicked === _id} className="open-dialog">
<CardTitle style={{color: '#fff', height: '176px', backgroundImage: `url(${blog_image_link})`, backgroundPosition: 'center',
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat'}}>{blog_name}</CardTitle>
<CardText>
{blog_desc}
</CardText>
<CardActions border>
<p style={{float:'right', fontWeight:'bold'}}>Author: {blog_by}</p>
</CardActions>
<CardMenu style={{color: '#fff'}}>
<FABButton onClick={this.handleCloseDialog} className="close-button" >
<Icon name="close" />
</FABButton>
</CardMenu>
</Dialog>
</Cell>
))}
</Grid>
)
}
render(){
const { blogs, loading} = this.props.resume;
const { isAuthenticated, user } = this.props.auth;
const itemsPerPage = 1;
let activeBlogs = blogs.slice (itemsPerPage * this.state.activePage - itemsPerPage, itemsPerPage * this.state.activePage)
return(
<Container>
{loading ? (
<div><Loading/></div>
) : (
<div>
{/* blog modal */}
<BlogModal />
{/* card dialog */}
{this.cardDialog(blogs, user)}
<Grid style={{padding: 0}} id="todo">
{activeBlogs.map(({ _id, blog_name, blog_by, date }) => (
<Cell key={_id} data-id={_id}>
{ this.props.isAuthenticated && (user.is_admin === true) ?
<Button className="remove-btn"
color="danger"
size="sm"
onClick= {this.onDeleteBlogClick.bind(this, _id)}>
×
</Button> : null }
<Card shadow={5} className="cards-grid">
<CardTitle className="card-title-image"></CardTitle>
<CardText>
<b>{blog_name}</b>
</CardText>
<CardActions border>
<Button className="blog-read-me-button" onClick={this.handleOpenDialog.bind(this, _id)}>Read </Button>
<p style={{ fontStyle:'italic', fontWeight:'bold'}}>By-{blog_by} <span style={{float:'right',}}>{Moment(date).format('Do MMMM YYYY')}</span></p>
</CardActions>
</Card>
</Cell>
))}
</Grid>
</div>
)}
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={1}
totalItemsCount={2}
pageRangeDisplayed={1}
onChange={this.handlePageChange.bind(this)}
itemClass='page-item'
linkClass='page-link'
/>
</Container>
)
}
}
const mapStateToProps = (state) => ({
resume: state.resume,
isAuthenticated : state.auth.isAuthenticated,
auth: state.auth,
loading: state.apiCallsInProgress > 0
});
export default connect(mapStateToProps, {getBlog, deleteBlog }) (Blogs);
//current ui

This is the default style of react-js-pagination. You have to style it yourself. However as far as I see, you are using bootstrap in your application, so you could use their styles in the following way:
<Pagination
activePage={this.state.activePage}
itemsCountPerPage={1}
totalItemsCount={2}
pageRangeDisplayed={1}
onChange={this.handlePageChange.bind(this)}
itemClass='page-item'
linkClass='page-link'
/>

Related

How to use MUI v5+ with class-based react components?

We are trying to update our web application from material ui (v4) to mui (v5)
Using the available examples, we have managed for function based components, but it does not seem to work for class based components, and there is very little examples around on class based components and MUI.
Out pattern looks something like the below currently, but none of the styles are applied to the MUI components. The same pattern seems to work on a POC project with functional components.
The container file Login.js
import {connect} from 'react-redux'
import Layout from '../pages/login.js';
import { call } from '../reducers/helloWorld'
import { logIn, logOut } from "../reducers/userManagement"
const mapStateToProps = state => ({
user: state.userManagement.user,
requestState: state.helloWorld.requestState,
})
const mapDispatchToProps = dispatch => ({
helloWorld: () => dispatch(call()),
logIn: (user2) => dispatch(logIn(user2)),
logOut: () => dispatch(logOut()),
})
export default connect(mapStateToProps, mapDispatchToProps)(Layout)
the page file login.js
import React from "react";
import { Typography, Button, FormControlLabel, Checkbox, TextField, Grid, Paper} from '#mui/material';
import { styled } from '#mui/material/styles';
import theme from '../theme';
import classes from '../styles/login';
import logo from '../img/Ergopak-logo.png';
import { Navigate } from 'react-router-dom';
// SXprops
class Login extends React.Component {
state = {
email: "",
password: "",
showPassword: false,
navigateTo: ""
}
componentDidMount(){
const {logOut} = this.props
logOut()
}
goToHome(){
}
handleSubmit(e){
const {logIn} = this.props
console.log("handleSubmit pressed!!")
logIn({name: "Pieka"})
this.setState({navigateTo: <Navigate to="/home"/>})
}
setEmail(){
console.log("handleEmail pressed")
}
setPassword(){
console.log("setPassword pressed")
}
render(){
const {user, requestState} = this.props
const {email, password, showPassword, navigateTo} = this.state
console.log("requestState", requestState)
console.log("user", user)
console.log("that thing is, ", classes(theme).welcome)
return(
<div style={{backgroundColor: "green", height: "100%", position: "fixed", width: "100%"}}>
<Grid container direction = "column" alignItems="stretch" justifyContent="flex-start" style={{backgroundColor: "grey", height: "100%", display: "flex"}} >
{navigateTo}
<Grid item sx = {classes(theme).welcomeDiv}>
<div sx = {classes(theme).welcome} >Welcome To SightPlan </div>
</Grid>
<Grid item >
<img style={{maxHeight: "2em"}} src={logo} alt="logo" />
</Grid>
<Grid item sx = {classes(theme).centerDivs}>
<Typography>Please log in with your email address and password</Typography>
<TextField
sx={{
width: 400
}}
type="email"
value={email}
placeholder="Email"
onChange={(e) => this.setState({email: e.target.value})}
/>
<Grid container direction = "column" alignItems = "center">
<TextField
sx = {classes(theme).loginFields}
type= {showPassword ? "string" : "password"}
variant="standard"
value={password}
placeholder="Password"
onChange={(e) => this.setState({password: e.target.value})}
/>
<FormControlLabel
control={<Checkbox size="small" name="showClosed" />}
checked={showPassword}
label={<span style={{ fontSize: '0.8em' }}> Show password </span>}
onChange={e => this.setState({showPassword: !showPassword})}
style={{margin: "auto"}}
/>
</Grid>
<Button
sx = {classes(theme).loginButton}
type="submit" onClick={this.handleSubmit.bind(this)}
variant="contained"
color="primary"
>
Log In
</Button>
</Grid>
<Paper style = {{backgroundColor: "blue", borderRadius: "0em", display: "flex", flexDirection: "column"}} />
</Grid>
</div>
)}
}
export default styled(Login)({theme})
The styles file login.js
import commonstyles from "./common"
const styles = (theme) => ({
centerDivs: commonstyles(theme).centerDivs,
welcomeDiv: commonstyles(theme).welcomeDiv,
white: commonstyles(theme).white,
logo: {
margin: "auto",
marginTop: "2em",
marginBottom: "2em",
...commonstyles(theme).logo,
},
welcome: {
fontSize: "3em",
fontFamily: "Segoe UI",
color: "white",
marginBottom: "1em",
margin: theme.spacing(2),
textAlign: "center"
},
loginFields: {
...commonstyles(theme).textField,
width: "20em"
},
loginButton: {
...commonstyles(theme).button,
width: "10em"
},
myTextBox: {
...commonstyles(theme).textField,
// "& .MuiInputBase-root": {
// color: 'black',
// borderColor: "green"
// }
}
})
export default styles
the theme file theme.js
import { createTheme } from '#mui/material/styles';
const theme = createTheme({
palette: {
primary: {
main: "#065f92", // blue
},
secondary: {
main: "#F79007", // orange
},
error: {
main: "#d32f2f",
},
warning: {
main: "#ed6c02",
},
info: {
main: "#0288d1",
},
success: {
main: "#2e7d32",
},
},
spacing: (factor) => `${factor}rem`,
});
export default theme;
and finally the App.js file that pulls it all together:
import React from "react";
import { Provider } from 'react-redux'
import theme from './theme';
import { ThemeProvider } from '#mui/material/styles';
import "./App.css";
import store from "./app/store";
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Login from "./containers/Login";
function App() {
return (
<ThemeProvider theme={theme}>
<Provider store={store}>
<div className="App" style={{maxHeight: "80%"}}>
<Router>
<Routes>
<Route path="/" element={<Login />} />
<Route path="/login" element={<Login />} /></Routes>
</Router>
<div style={{clear:"both", "height": "40px"}}></div>
</div>
</Provider>
</ThemeProvider>
);
}
export default App;

How to call a component from an onClick event

I would like to make it possible that whenever I click on a button (which is a component itself) a modal component is called. I did some research but none of the solutions is doing what I need. It partially works but not quite the way I want it to because, once the state is set to true and I modify the quantity in the Meals.js and click again the modal doesn't show up
Meals.js
import React, { useState } from "react";
import { Card } from "react-bootstrap";
import { Link } from "react-router-dom";
import NumericInput from "react-numeric-input";
import AddBtn from "./AddtoCartBTN";
function Meals({ product }) {
const [Food, setFood] = useState(0);
return (
<Card className="my-3 p-3 rounded">
<Link to={`/product/${product.id}`}>
<Card.Img src={product.image} />
</Link>
<Card.Body>
<Link to={`/product/${product.id}`} style={{ textDecoration: "none" }}>
<Card.Title as="div">
<strong>{product.name}</strong>
</Card.Title>
</Link>
Quantity{" "}
<NumericInput min={0} max={100} onChange={(value) => setFood(value)} />
{/* <NumericInput min={0} max={100} onChange={ChangeHandler(value)} /> */}
<Card.Text as="h6" style={{ color: "red" }}>
{Food === 0 ? product.price : Food * product.price} CFA
</Card.Text>
<AddBtn quantity={Food} price={product.price} productId={product.id} />
</Card.Body>
</Card>
);
}
export default Meals;
AddToCartBtn.js
import React, { useEffect, useState } from "react";
import { useDispatch } from "react-redux";
import { addToCart } from "../actions/cmdActions";
import toast, { Toaster } from "react-hot-toast";
import CartModal from "./CartModal";
function AddtoCartBTN({ quantity, price, productId }) {
const AddedPrice = quantity * price;
const [showModal, setShowModal] = useState(false)
const notify = () => toast("Ajout Effectue !", {});
const dispatch = useDispatch();
const AddtoCart = () => {
// console.log("Added to cart !");
// console.log("Added : ", AddedPrice);
if (AddedPrice > 0) {
dispatch(addToCart(productId, AddedPrice));
notify();
setShowModal(true)
}
};
return (
<button
className="btn btn-primary d-flex justify-content-center"
onClick={AddtoCart}
>
Ajouter
{showModal && <CartModal/>}
<Toaster />
</button>
);
}
export default AddtoCartBTN;
Modal.js
import React, { useState } from "react";
import { Modal, Button, Row, Col } from "react-bootstrap";
import { useSelector } from "react-redux";
import { useHistory } from "react-router-dom";
function CartModal () {
const [modalShow, setModalShow] = useState(true);
let history = useHistory();
const panierHandler = () => {
history.push('/commander')
}
const cart = useSelector((state) => state.cart);
const { cartItems } = cart;
function MyVerticallyCenteredModal(props) {
return (
<Modal
{...props}
size="md"
aria-labelledby="contained-modal-title-vcenter"
centered
backdrop="static"
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
<b style={{ color: "red" }}> choix de produits</b> <br />
</Modal.Title>
</Modal.Header>
<Modal.Body>
<Row>
<Col><b>Nom</b></Col>
<Col><b>Quantite</b></Col>
</Row><hr/>
{cartItems && cartItems.map((item,i)=>(
<>
<Row key={i}>
<Col>{item.name}</Col>
<Col>{item.total / item.price}</Col>
</Row><hr/>
</>
))}
</Modal.Body>
<Modal.Footer
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Button
// onClick={props.onHide}
onClick={panierHandler}
>
Aller au Panier
</Button>
</Modal.Footer>
</Modal>
);
}
return (
<>
<MyVerticallyCenteredModal
show={modalShow}
onHide={() => setModalShow(false)}
/>
</>
);
}
export default CartModal
in AddToCartBtn.js, you can pass setShowModal as a prop.
{showModal && <CartModal setShowModal={setShowModal} />}
And the, in Modal.js, you can use the prop setShowModal to set the value to false
<MyVerticallyCenteredModal show={true} onHide={() => setShowModal(false)} />
Eliminate the state in Modal.js, keep visible as always true

Not able to call onChange function of a TextInput in Redux, React JS

I am working on an app with React and Redux and displaying some data from API in TextInput control. But now I am not able to edit the data in the TextInput. Following is my complete code of the class:
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import Article from "grommet/components/Article";
import Box from "grommet/components/Box";
import Button from "grommet/components/Button";
import Header from "grommet/components/Header";
import Heading from "grommet/components/Heading";
import Section from "grommet/components/Section";
import AdminMenu from "../../components/Nav/Admin";
import NavControl from "../../components/Nav/Control";
import { getMessage } from "grommet/utils/Intl";
import Notices from "../../components/Notices";
import CheckBox from "grommet/components/CheckBox";
import TextInput from "grommet/components/TextInput";
import { pageLoaded } from "../utils";
import {
recognitionSettingsLoaded,
recognitionSettingsSaved,
} from "../../actions/settings-recognition";
import dashboard from "../../reducers/dashboard";
class Settings extends Component {
constructor(props) {
super(props);
this.handleDaysChange = this.handleDaysChange.bind(this);
this.handleActiveChange = this.handleActiveChange.bind(this);
}
componentDidMount() {
const { dispatch, settingRecognition } = this.props;
console.log(this.props.state);
console.log(dashboard);
dispatch(recognitionSettingsLoaded("2"));
pageLoaded("Configuration");
}
onSave() {
const { survey, dispatch } = this.props;
dispatch(
recognitionSettingsSaved(
this.props.settingRecognition.days,
this.props.settingRecognition.active
)
);
}
handleDaysChange(e) {
const days = e.target.value;
settingRecognition.days = days;
}
handleActiveChange(e) {
const active = e.target.value;
settingRecognition.active = active;
}
render() {
const { dispatch, settingRecognition } = this.props;
console.log("render method");
console.log(settingRecognition);
const { intl } = this.context;
return (
<Article primary={true}>
<Header
direction="row"
justify="between"
size="large"
pad={{ horizontal: "medium", between: "small" }}
>
<NavControl name={getMessage(intl, "Configuration")} />
<AdminMenu />
</Header>
<Box pad={{ horizontal: "medium", vertical: "medium" }}>
<Heading tag="h4" margin="none">
{getMessage(intl, "RecognitionLifetime")}
</Heading>
<Heading tag="h5" margin="none">
{getMessage(intl, "DefineIsRecognitionTemporary")}
</Heading>
<Box direction="row">
<CheckBox
toggle={true}
checked={settingRecognition.active}
onChange={this.handleActiveChange}
/>{" "}
<Heading tag="h3" margin="none">
{getMessage(intl, "NewUserActive")}
</Heading>
</Box>
<Heading tag="h3" margin="none">
{getMessage(intl, "HideAfter")}
</Heading>
<Box direction="row">
<TextInput
placeholder="type here"
value={settingRecognition.days.toString()}
onChange={this.handleDaysChange}
/>{" "}
<Heading tag="h3" margin="none">
{getMessage(intl, "Days")}
</Heading>
</Box>
<Button
path="/recognition-settings"
label={getMessage(intl, "NewUserSave")}
primary={true}
onClick={() => {
this.onSave();
}}
/>
</Box>
<Notices />
</Article>
);
}
}
Settings.propTypes = {
dispatch: PropTypes.func.isRequired,
settingRecognition: PropTypes.object.isRequired,
};
Settings.contextTypes = {
intl: PropTypes.object,
};
const mapStateToProps = (state) => ({
settingRecognition: state.settingRecognition,
});
export default connect(mapStateToProps)(Settings);
I have created handleDaysChange function which should run on the text change of TextInput control. I have done similar thing for the checkbox and that works fine but I am not able to get it working for the TextInput.
You are not binding your change events.
Try this....
class Settings extends Component {
constructor(props){
super(props);
this.handleDaysChange = this.handleDaysChange.bind(this);
this.handleActiveChange = this.handleActiveChange.bind(this);
}
componentDidMount(){
....
}
......
}
and change this
<CheckBox
toggle={true}
checked={settingRecognition.active}
onChange={(e) => this.handleActiveChange(e)}
/>
To this
<CheckBox
toggle={true}
checked={settingRecognition.active}
onChange={this.handleActiveChange}
/>
same for text input
<TextInput
placeholder="type here"
value={settingRecognition.days.toString()}
onChange={this.handleDaysChange}
/>
You need to set up two-way-binding so that the content of the textInput reflects the prop that you set in your onChange function. Try giving your textInput a property of value={this.settingRecognition.days}

how to edit and delete in api data table in reactjs

I am new to React. Currently, I am doing API fetch and displaying it in a table and adding edit delete in that table. I am successfully fetching API and I can add a new row along with API data, but I don't know how to edit and delete it. I have seen some questions but my code structure is different so I am unable to find the answer. Does any help please?
here is my code,
import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import { makeStyles,withStyles } from '#material-ui/core/styles';
import Fab from '#material-ui/core/Fab';
import AddIcon from '#material-ui/icons/Add';
import EditIcon from '#material-ui/icons/Edit';
import TextField from '#material-ui/core/TextField';
import Dialog from '#material-ui/core/Dialog';
import DialogActions from '#material-ui/core/DialogActions';
import DialogContent from '#material-ui/core/DialogContent';
import DialogContentText from '#material-ui/core/DialogContentText';
import DialogTitle from '#material-ui/core/DialogTitle';
import Button from '#material-ui/core/Button';
const useStyles = theme => ({
fab: {
margin: theme.spacing(1),
},
extendedIcon: {
marginRight: theme.spacing(1),
},
});
const Post = ({ body }) => {
  return (
    <table className=" table-striped">
      <thead>
       <tr>
      <th>Id</th>
      <th>Title</th>
      <th>Content</th>
      
      </tr>
      </thead>
      <tbody>
{body.map(post => {
const { _id, title, content } = post;
return (
 <tr key={_id}>
            <td> {_id!=''?_id: '-'}</td>
            
            <td> {title!='' ?title: '-'}</td>
            
            <td> {content!=''?content: '-'}</td>
<hr />
</tr>
);
})}
</tbody>
</table>
);
};
class App extends React.Component {
state = {
isLoading: true,
posts: [],
error: null,
open:false,
newData:[
{
_id:'',
title:'',
content:''
}
]
};
fetchPosts() {
const axios = require('axios');
axios
.get("https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/posts.json")
.then(response => {
this.setState({
posts: response.data.posts,
isLoading: false,
})
//)
} )
}
componentDidMount() {
this.fetchPosts();
}
handleClickOpen = () =>
this.setState({
open:true
})
;
handleClose = () =>
this.setState({
open:false
})
;
// handleClick = () =>
// {
// {this.handleClickOpen}
// {this.addItem}
// }
// ;
addItem = () =>
{
var temp = [];
var tempPosts = this.state.posts;
var newData = this.state.newData[0];
console.log(this.state.newData)
if(this.state.newData[0]._id && this.state.newData[0].title && this.state.newData[0].content){
tempPosts.push(newData);
console.log(tempPosts)
this.setState({posts: tempPosts})
}
}
render() {
const { isLoading, posts } = this.state;
return (
<React.Fragment>
<h1>React Fetch - Blog</h1>
<div>
<Button variant="outlined" color="primary" onClick=
{this.handleClickOpen}
>
Add
</Button>
<Dialog open={this.state.open} onClose={this.handleClose} aria-labelledby="form-dialog-title">
<DialogTitle id="form-dialog-title">Subscribe</DialogTitle>
<DialogContent>
<TextField
autoFocus
margin="dense"
id="_id"
label="id"
value={this.state.newData._id}
onChange={(e)=> {
let{ newData } = this.state;
newData[0]._id=e.target.value;
this.setState({newData})
}}
type="text"
fullWidth
/>
<TextField
autoFocus
margin="dense"
id="title"
label="title"
value={this.state.newData.title}
onChange={(e)=> {
let{newData} =this.state;
newData[0].title=e.target.value;
this.setState({newData})
}}
type="text"
fullWidth
/>
<TextField
autoFocus
margin="dense"
id="content"
label="content"
value={this.state.newData.content}
onChange={(e)=> {
let{newData} =this.state;
newData[0].content=e.target.value;
this.setState({newData})
}}
type="text"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button
onClick={() => {
this.addItem()
this.handleClose()
}}
color="primary">
Add
</Button>
<Button onClick={this.handleClose} color="primary">
cancel
</Button>
</DialogActions>
</Dialog>
</div>
<hr />
{!isLoading ? <Post body={posts} /> : <h3>Loading...</h3>}
</React.Fragment>
);
}
}
export default withStyles(useStyles)(App);

Transforming values from react template for further use in states

This might be a duplicate question but I still couldn't find an answer. I am new to react and is struggling to create a login page. I am trying t set states with the values I have just entered in the application for further usage. Using these values I will be making a backed call for authentication.
My React Code
import React from "react";
// core components are added
class LoginPage extends React.Component {
constructor(props) {
super(props);
// we use this to make the card to appear after the page has been rendered
this.state = {
cardAnimaton: "cardHidden"
};
}
handleSubmit() {
console.log(this);
}
handleChange(event) {
console.log(event)
}
componentDidMount() {
// we add a hidden class to the card and after 700 ms we delete it and the transition appears
setTimeout(
function() {
this.setState({ cardAnimaton: "" });
}.bind(this),
700
);
}
render() {
const { classes, ...rest } = this.props;
return (
<div>
<div className={classes.container}>
<GridContainer justify="center">
<GridItem xs={12} sm={12} md={12}>
<Card className={classes[this.state.cardAnimaton]}>
<form className={classes.form} onSubmit = {this.handleSubmit}>
<CardHeader color="primary" className={classes.cardHeader}>
<h4>Login</h4>
</CardHeader>
<CardBody>
<CustomInput
labelText="Email..."
id="email"
onChange={this.handleChange}
value = {this.state.email}
formControlProps={{
fullWidth: true
}}
inputProps={{
type: "email",
endAdornment: (
<InputAdornment position="end">
<Email className={classes.inputIconsColor} />
</InputAdornment>
)
}}
/>
</CardBody>
<CardFooter className={classes.cardFooter}>
<Button color="primary" size="lg" type="submit">
Login
</Button>
</CardFooter>
</form>
</Card>
</GridItem>
</GridContainer>
</div>
</div>
);
}
}
export default withStyles(loginPageStyle)(LoginPage);
I am trying to send values from my HTML to state in handleChange but it is not reacting whenever I make a change.
If it something with states, please let me know. I am using a custom theme and hope that the issue is in my implementation and have nothing to do with the theme.
Custom Input Component
import React from "react";
// nodejs library to set properties for components
import PropTypes from "prop-types";
// nodejs library that concatenates classes
import classNames from "classnames";
// #material-ui/core components
import withStyles from "#material-ui/core/styles/withStyles";
import FormControl from "#material-ui/core/FormControl";
import InputLabel from "#material-ui/core/InputLabel";
import Input from "#material-ui/core/Input";
import customInputStyle from "assets/jss/material-kit-react/components/customInputStyle.jsx";
function CustomInput({ ...props }) {
const {
classes,
formControlProps,
labelText,
id,
labelProps,
inputProps,
error,
white,
inputRootCustomClasses,
success
} = props;
const labelClasses = classNames({
[" " + classes.labelRootError]: error,
[" " + classes.labelRootSuccess]: success && !error
});
const underlineClasses = classNames({
[classes.underlineError]: error,
[classes.underlineSuccess]: success && !error,
[classes.underline]: true,
[classes.whiteUnderline]: white
});
const marginTop = classNames({
[inputRootCustomClasses]: inputRootCustomClasses !== undefined
});
const inputClasses = classNames({
[classes.input]: true,
[classes.whiteInput]: white
});
var formControlClasses;
if (formControlProps !== undefined) {
formControlClasses = classNames(
formControlProps.className,
classes.formControl
);
} else {
formControlClasses = classes.formControl;
}
return (
<FormControl {...formControlProps} className={formControlClasses}>
{labelText !== undefined ? (
<InputLabel
className={classes.labelRoot + " " + labelClasses}
htmlFor={id}
{...labelProps}
>
{labelText}
</InputLabel>
) : null}
<Input
classes={{
input: inputClasses,
root: marginTop,
disabled: classes.disabled,
underline: underlineClasses
}}
id={id}
{...inputProps}
/>
</FormControl>
);
}
CustomInput.propTypes = {
classes: PropTypes.object.isRequired,
labelText: PropTypes.node,
labelProps: PropTypes.object,
id: PropTypes.string,
inputProps: PropTypes.object,
formControlProps: PropTypes.object,
inputRootCustomClasses: PropTypes.string,
error: PropTypes.bool,
success: PropTypes.bool,
white: PropTypes.bool
};
export default withStyles(customInputStyle)(CustomInput);

Categories

Resources