How to call a component from an onClick event - javascript

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

Related

Products Update using Redux When click on " Category" name one Mega Menu, MegaMenu And Product both are different components

Please See the >>
I want to update Products by clicking on Category Name the MegaMenu, But it does not change. I use redux for state management. Please help me !!
This is MegaMenu Component
import MenuIcon from '#mui/icons-material/Menu';
import './MegaMenu.css';
import { NavLink } from 'react-router-dom';
import ArrowRightIcon from '#mui/icons-material/ArrowRight';
const categories = [
"Sunglass",
"Footwear",
"Men Watch",
"Women Watch",
"Computer",
"SmartPhones",
"Camera",
];
const MegaMenu = () => {
return (
<div className='mega_menu_component'>
<div className='mega_menu_Items'>
<div className='mega_menus'>
<MenuIcon className='mega_menu_icon' style={{ fontSize: '40px', color: '#fff', cursor: 'pointer' }} />
<div class="menu_link_content">
<NavLink className="menu_name" to="/">Home</NavLink>
<NavLink className="menu_name" to="/products">Shop <ArrowRightIcon style={{ fontSize: 'medium' }} />
<ul className="categoryMenu">
{categories.map((categoryName) => (
<li className="categoryMenu-link" > <NavLink style={{ textDecoration: 'none', color: '#000' }} key={categoryName} to={`/products/${categoryName}`}>{categoryName}</NavLink></li>
))}
</ul>
</NavLink>
<NavLink className="menu_name" to="/contact">Contact</NavLink>
<NavLink className="menu_name" to="/about">About</NavLink>
</div>
</div>
</div>
</div>
);
};
export default MegaMenu;
This is Products component
import React, { Fragment, useEffect, useState } from "react";
import "./Products.css";
import { useSelector, useDispatch } from "react-redux";
import { clearErrors, getProduct } from "../../actions/productAction";
import Loader from "../layout/Loader/Loader";
import ProductCard from "../Home/ProductCard";
import Pagination from "react-js-pagination";
import Slider from "#material-ui/core/Slider";
import { useAlert } from "react-alert";
import Typography from "#material-ui/core/Typography";
import MetaData from "../layout/MetaData";
import { useParams } from "react-router";
import { NavLink, useLocation } from "react-router-dom"
const categories = [
"Sunglass",
"Footwear",
"Men Watch",
"Women Watch",
"Computer",
"SmartPhones",
"Camera",
];
const Products = ({ match }) => {
const dispatch = useDispatch();
const urlLocation = useLocation();
const categoryName = urlLocation.pathname.split('/')[2];
const alert = useAlert();
const [currentPage, setCurrentPage] = useState(1);
const [price, setPrice] = useState([0, 25000]);
// const [category, setCategory] = useState(categoryName);
const [category, setCategory] = useState('');
const [ratings, setRatings] = useState(0);
const {
products,
loading,
error,
productsCount,
resultPerPage,
filteredProductsCount,
} = useSelector((state) => state.products);
const keyword = match.params.keyword;
const setCurrentPageNo = (e) => {
setCurrentPage(e);
};
const priceHandler = (event, newPrice) => {
setPrice(newPrice);
};
let count = filteredProductsCount;
useEffect(() => {
if (error) {
alert.error(error);
dispatch(clearErrors());
}
dispatch(getProduct(keyword, currentPage, price, category, ratings));
}, [dispatch, keyword, currentPage, price, category, ratings, alert, error]);
return (
<Fragment>
{loading ? (
<Loader />
) : (
<Fragment>
<MetaData title="PRODUCTS -- ECOMMERCE" />
<h2 className="productsHeading">Products</h2>
<div className="products">
{products &&
products.map((product) => (
<ProductCard key={product._id} product={product} />
))}
</div>
<div className="filterBox">
<Typography>Price</Typography>
<Slider
value={price}
onChange={priceHandler}
valueLabelDisplay="auto"
aria-labelledby="range-slider"
min={0}
max={25000}
/>
<Typography>Categories</Typography>
<ul className="categoryBox">
{categories.map((category) => (
<li className="category-link" >
<NavLink style={{ textDecoration: 'none', color: 'black' }} key={category} onClick={() => setCategory(category)} to={`/products`}>{category}</NavLink>
</li>
))}
</ul>
<fieldset>
<Typography component="legend">Ratings Above</Typography>
<Slider
value={ratings}
onChange={(e, newRating) => {
setRatings(newRating);
}}
aria-labelledby="continuous-slider"
valueLabelDisplay="auto"
min={0}
max={5}
/>
</fieldset>
</div>
{resultPerPage < count && (
<div className="paginationBox">
<Pagination
activePage={currentPage}
itemsCountPerPage={resultPerPage}
totalItemsCount={productsCount}
onChange={setCurrentPageNo}
nextPageText="Next"
prevPageText="Prev"
firstPageText="1st"
lastPageText="Last"
itemClass="page-item"
linkClass="page-link"
activeClass="pageItemActive"
activeLinkClass="pageLinkActive"
/>
</div>
)}
</Fragment>
)}
</Fragment>
);
};
export default Products;
** When I want to click on the mega menu "Shop>>Category" name the URL would be like http://localhost:3000/products/Sunglass Here sunglass is the category name **
** Now I want to data update in the Product component (ProductCard Update) using the URL category part. But it does not work. **

Side Navigation bar jumps to top after selecting specific page from Navigation bar

I am having an issue with Navigation Bar jumping to the top after selecting specific page. I want to side bar to stay same position after selecting the page. I found few similar questions here but the given solutions didn't solve my issue. Here the Code.
SideBarItem.js
import React, { useState } from 'react';
import classnames from 'classnames';
import { useRouter } from 'next/router';
import Link from 'next/link';
import useTranslation from 'next-translate/useTranslation';
import { AiOutlineLeft, AiOutlineDown } from 'react-icons/ai';
const SidebarHeader = ({ toggleSideBar, transKey }) => {
const { t } = useTranslation();
return (
<li
name={transKey}
id={transKey}
className={classnames('nav-small-cap', { 'dots-icon': !toggleSideBar })}>
{!toggleSideBar && <i className="mdi mdi-dots-horizontal"></i>}
{toggleSideBar && <span className="hide-menu">{t(transKey)}</span>}
</li>
);
};
const SidebarItem = ({
route,
icon,
toggleSideBar,
transKey,
isHeader,
subs,
}) => {
const { t } = useTranslation();
const router = useRouter();
const [isOpen, setIsOpen] = useState(false);
const handleToggle = () => {
setIsOpen(!isOpen);
};
const selectedClassName = router.pathname === route ? 'selected' : null;
return (
<>
{isHeader && (
<SidebarHeader
toggleSideBar={toggleSideBar}
transKey={transKey}
id={transKey}
/>
)}
{!isHeader && (
<li className={classnames('sidebar-item', selectedClassName)}>
<div className="sidebar-link clickable text-white-100 waves-effect waves-dark">
<i className={icon} style={{ color: 'white' }}></i>
{toggleSideBar && (
<div className="arrow-style">
{!subs && (
<Link href={route}>
<a className="hide-menu"> {t(transKey)}</a>
</Link>
)}
{subs && (
<>
<a className="hide-menu" onClick={handleToggle}>
{t(transKey)}
</a>
<div className="sidebar-arrow">
{isOpen ? <AiOutlineDown /> : <AiOutlineLeft />}
</div>
</>
)}
</div>
)}
</div>
{subs && (
<ul
className={classnames('collapse', 'first-level', {
show: isOpen,
})}>
{subs.map((subNavItem) => (
<SidebarItem
key={subNavItem.transKey}
{...subNavItem}
toggleSideBar={toggleSideBar}
/>
))}
</ul>
)}
</li>
)}
</>
);
};
export default SidebarItem;
SidebarLinks.js file
import React from 'react';
import navItems from '#constants/navItems';
import SidebarItem from './SidebarItem';
const SidebarLinks = (props) => {
return (
<nav className="sidebar-nav">
<ul id="sidebarnav" className="in">
{navItems.map((navItem) => (
<SidebarItem key={navItem.transKey} {...navItem} {...props} />
))}
</ul>
</nav>
);
};
export default SidebarLinks;
LayoutWithSidebar.js file
import React from 'react';
import useTranslation from 'next-translate/useTranslation';
import SidebarFooter from '#components/Sidebar/SidebarFooter';
import UserProfile from '#components/Sidebar/UserProfile';
import SidebarLinks from '#components/Sidebar/SidebarLinks';
import Styles from './styles';
const LayoutWithSidebar = ({ toggleSideBar, setToggleSidebar, btn }) => {
const { t } = useTranslation();
const handleEnterMouse = () => {
setToggleSidebar(true);
};
return (
<aside
className={`left-sidebar-style ${
toggleSideBar ? 'open-left-sidebar' : 'left-sidebar'
}`}
onMouseEnter={handleEnterMouse}
data-sidebarbg="skin5">
<div className="scroll-sidebar">
<UserProfile btn={btn} toggleSideBar={toggleSideBar} translation={t} />
<SidebarLinks btn={btn} toggleSideBar={toggleSideBar} translation={t} />
</div>
{(toggleSideBar || btn) && <SidebarFooter />}
<style jsx toggleSideBar={toggleSideBar}>
{Styles}
</style>
</aside>
);
};
export default LayoutWithSidebar;
App.js file
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { Row, Col } from 'reactstrap';
import useTranslation from 'next-translate/useTranslation';
import AccountOverview from '#components/Dashboard/AccountOverview';
import Exposure from '#components/Dashboard/Exposure';
import PerformanceStats from '#components/Dashboard/PerformanceStats';
import CommissionAndBalance from '#components/Dashboard/CommissionAndBalance';
import MostRecentConversions from '#components/Dashboard/MostRecentConversions/index';
import Announcement from '#components/Dashboard/Announcement';
import TopPublishers from '#components/Dashboard/TopPublishers';
import ClickByCountries from '#components/Dashboard/TotalVisits/index';
import ClickPerDevice from '#components/Dashboard/OurVisitors/index';
import useShallowEqualSelector from '#hooks/useShallowEqualSelector';
import BaseLayout from '#layouts/BaseLayout';
import { formatNumber } from '#utils';
import routes from '#constants/routes';
import {
fetchAccountOverviewDataAction,
fetchPerformanceStatAction,
fetchAnnouncementAction,
fetchCommissionBalanceAction,
fetchExposuresAction,
fetchRecentConversionAction,
fetchTopPublishersAction,
fetchVisitorDataAction,
} from '#actions';
const Dashboard = () => {
const { t } = useTranslation();
const dispatch = useDispatch();
const [announcementRole, setAnnouncementRole] = useState('advertiser');
const [statFilter, setStatFilter] = useState('day');
const {
accountOverview,
exposures,
visitors,
commissionBalance,
recentConversions,
topPublishers,
performanceStatistics,
} = useShallowEqualSelector(({ stat }) => {
return stat;
});
const {
fetch: { list: announcements, status: announcementFetchStatus },
} = useShallowEqualSelector((state) => state.announcements);
const {
get: { currencyCode },
} = useShallowEqualSelector((state) => state.stat?.recentConversions);
useEffect(() => {
dispatch(fetchCommissionBalanceAction());
dispatch(fetchRecentConversionAction());
}, [dispatch]);
useEffect(() => {
dispatch(fetchAccountOverviewDataAction());
dispatch(fetchExposuresAction());
dispatch(fetchTopPublishersAction());
dispatch(fetchVisitorDataAction());
}, [dispatch]);
useEffect(() => {
dispatch(fetchPerformanceStatAction({ filter: statFilter }));
}, [dispatch, statFilter]);
useEffect(() => {
dispatch(
fetchAnnouncementAction({ role: announcementRole, page: 1, perPage: 4 })
);
}, [dispatch, announcementRole]);
return (
<BaseLayout
metaPageTitle={t('dashboard:pageTitle')}
pageTitle={t('dashboard:pageTitle')}
pageSubtitle={t('dashboard:pageSubtitle')}
breadcrumbPaths={[
{ url: routes.dashboard.url, text: t('common:home') },
{ text: t('dashboard:pageTitle') },
]}>
<div className="container-fluid">
{
<Row>
<Col sm={12}>
<AccountOverview
accountOverview={accountOverview.get.data}
isLoading={accountOverview.get.status === 'loading'}
t={t}
/>
</Col>
</Row>
}
{
<Row>
<Col sm={12}>
<PerformanceStats
isLoading={performanceStatistics.get.status === 'loading'}
setStatFilter={setStatFilter}
statFilter={statFilter}
performanceStatistics={performanceStatistics.get.data}
t={t}
/>
</Col>
</Row>
}
{
<Row>
<Col sm={12}>
<Exposure
exposures={exposures.get.data}
isLoading={exposures.get.status === 'loading'}
t={t}
/>
</Col>
</Row>
}
{
<Row>
<Col sm={12}>
<CommissionAndBalance
commissionBalance={commissionBalance.get.data}
isLoading={commissionBalance.get.status === 'loading'}
t={t}
/>
</Col>
</Row>
}
<Row>
<Col sm={12}>
<MostRecentConversions
isLoading={recentConversions.get.status === 'loading'}
recentConversions={recentConversions.get.data}
t={t}
currencyCode={currencyCode}
/>
</Col>
</Row>
<Row>
<Col sm={12}>
<div className="card-deck mb-4">
{
<Announcement
announcements={announcements}
announcementRole={announcementRole}
isLoading={announcementFetchStatus === 'loading'}
setAnnouncementRole={setAnnouncementRole}
t={t}
/>
}
<TopPublishers
isLoading={topPublishers.get.status === 'loading'}
topPublishers={topPublishers.get.data}
t={t}
formatNumber={formatNumber}
format
/>
</div>
</Col>
</Row>
{
<Row>
<Col sm={6}>
<ClickByCountries
isLoading={visitors.get.status === 'loading'}
totalVisitors={visitors.get.data?.totalVisitors}
t={t}
/>
</Col>
<Col sm={6}>
<ClickPerDevice
isLoading={visitors.get.status === 'loading'}
ourVisitors={visitors.get.data?.ourVisitors}
t={t}
/>
</Col>
</Row>
}
</div>
</BaseLayout>
);
};
export default Dashboard;
It would be great if you can assist.
P.S. I already looked through some answers here but it didn't work for me.
PLS check video link below
https://www.youtube.com/shorts/4xzlBfhQcKQ
From the video that you showed and the code you shared it seems that you wrapped your sidebar along with the entire application and pages components. If you want to avoid "rerendering" the sidebar, which is the thing that applies the "go to the top" effect, you should unwrap the layout with sidebar from the route changing, this will prevent this behaviour.

React-Bootstrap - How to create rows of 4 cards each?

how do I set the number of cards per row? I need 4 cards to be in one row of mine.
I have been trying for hours.. can't figure out what i do wrong..
I was getting all sorts of errors when i played around with this.
like this one :
here
my package.json file:
thanks!
:)
import { React } from 'react';
import { Card, Button, CardGroup } from 'react-bootstrap';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
const MyDishes = props => {
const { dishes } = props;
return (
<CardGroup style={{display: 'flex', flexDirection: 'row'}}>
{dishes.length > 0 &&
dishes.map(d => (
<Row xs={1} md={2} className="g-4">
{Array.from({ length: 4 }).map((_, idx) => (
<Col>
<Card key={d.id} style={{ width: '100em' }} style={{flex: 1}}>
<Card.Img variant="top" src={d.attributes.picture} />
<Card.Body>
<Card.Title>{d.attributes.name}</Card.Title>
<Card.Text>Possibly some text here</Card.Text>
<Link to={`/dishes/${d.id}`}>
<Button variant="primary">Full Recipe</Button>
</Link>
</Card.Body>
</Card>
</Col>
))}
</Row>
</CardGroup>
);
};
const mapStateToProps = state => {
return {
dishes: state.myDishes
};
};
export default connect(mapStateToProps)(MyDishes);
i get this error now :
To use bootstrap layout system, must use <Container> to wrap <Row> and <Col>
You don't need custom styles to achieve that you want.
import { React } from 'react';
import { Container, Card, Button, CardGroup } from 'react-bootstrap';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
const MyDishes = props => {
const { dishes } = props;
return (
<Container>
{dishes.length > 0 &&
dishes.map(d => (
<Row xs={1} md={2} className="g-4">
{Array.from({ length: 4 }).map((_, idx) => (
<Col>
<Card key={d.id}>
<Card.Img variant="top" src={d.attributes.picture} />
<Card.Body>
<Card.Title>{d.attributes.name}</Card.Title>
<Card.Text>Possibly some text here</Card.Text>
<Link to={`/dishes/${d.id}`}>
<Button variant="primary">Full Recipe</Button>
</Link>
</Card.Body>
</Card>
</Col>
))}
</Row>
))}
</Container>
);
};
const mapStateToProps = state => {
return {
dishes: state.myDishes
};
};
export default connect(mapStateToProps)(MyDishes);

How to use pagination in Reactjs application

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'
/>

Reuse in the react

I need to reuse some basic components to avoid code duplication but some examples are not serving me
the problem is here const [cpf, setCpf] = useState (data.cpf);
this data.cpf is getting information from an api but not filling the const as initial value
HOC
const onHandleChange = onChange => event => {
const { value } = event.target;
onChange(value);
};
Field:
export const Field = ({ component: Component, onChange, ...props }) => (
<div>
<Component onChange={onHandleChange(onChange)} {...props} />
</div>
);
InputField:
import React, { useState } from "react";
//Componentes
import { InputGroup, Button, FormControl } from "react-bootstrap";
import EditIcon from "#material-ui/icons/Edit";
import CheckIcon from "#material-ui/icons/Check";
export function InputField({ value, name, type, onChange }) {
const [teste, setTeste] = useState(true);
function click(e) {
setTeste(!teste);
}
return (
<div>
<InputGroup>
<InputGroup.Prepend>
<InputGroup.Text
style={{
backgroundColor: "white",
borderStyle: "hidden"
}}
>
{name}
</InputGroup.Text>
</InputGroup.Prepend>
<FormControl
style={{ borderStyle: "hidden" }}
disabled={teste}
value={value}
type={type}
onChange={onChange}
/>
<InputGroup.Append>
{teste === true ? (
<Button variant="white" onClick={click}>
<EditIcon />
</Button>
) : (
<Button variant="white" onClick={click}>
<CheckIcon />
</Button>
)}
</InputGroup.Append>
</InputGroup>
</div>
);
}
ViewClient:
import React, { useState } from "react";
//UI-Components
import { Modal, Card, ListGroup, Button } from "react-bootstrap";
import Account from "#material-ui/icons/AccountCircle";
//Reecriação de componentes
import { Field } from "./Components/Input";
import { InputField } from "./Components/InputFieldComponent";
//Redux
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
//Creators
import { Creators as ClientActions } from "../../../redux/store/ducks/cliente";
import { Creators as MapActions } from "../../../redux/store/ducks/map";
import { Creators as CaboActions } from "../../../redux/store/ducks/cabo";
function ViewClient(props) {
const { viewClient } = props.redux.client;
const { data } = viewClient; //Informações do usuario.
const [cpf, setCpf] = useState(data.cpf);
const [name, setName] = useState(data.name);
function handleHideModal() {
const { hideClientViewModal } = props;
hideClientViewModal();
}
function changeActive() {
console.log(cpf);
}
return (
<>
<Modal size="lg" show={viewClient.visible} onHide={handleHideModal}>
<Modal.Header
style={{
justifyContent: "center",
display: "flex",
flexDirection: "column",
alignItems: "center",
backgroundColor: "#F7D358"
}}
>
<h6 style={{ fontSize: "10px" }}>{data.created_at}</h6>
<Account
style={{
display: "block",
fontSize: "50px",
marginTop: "10px",
marginBottom: "10px"
}}
/>
<Modal.Title style={{ color: "#585858" }}>{data.name}</Modal.Title>
</Modal.Header>
<Modal.Body style={{ backgroundColor: "#FFFFFF" }}>
<Card style={{ width: "100%" }}>
<Card.Header
style={{ backgroundColor: "#D8D8D8", textAlign: "center" }}
>
Informações do cliente
</Card.Header>
<ListGroup variant="flush">
<ListGroup.Item>
<Field
component={InputField}
name={cpf}
type={"text"}
value={cpf}
onChange={setCpf}
/>
</ListGroup.Item>
<ListGroup.Item>
<Field
component={InputField}
name={"Nome"}
type={"text"}
value={name}
onChange={setName}
/>
</ListGroup.Item>
</ListGroup>
</Card>
</Modal.Body>
<Modal.Footer>
<Button variant="info">Salvar Alterações</Button>
{data.status === null ? (
<Button variant="primary" onClick={changeActive}>
Ativar cliente
</Button>
) : (
<Button variant="danger" onClick={changeActive}>
Desativar
</Button>
)}
<Button variant="danger">Excluir</Button>
<Button variant="secondary">Adicionar Cabo</Button>
<Button variant="secondary">Fechar</Button>
</Modal.Footer>
</Modal>
</>
);
}
const mapStateToProps = state => ({
redux: state
});
//Ações
const mapDispatchToProps = dispatch =>
bindActionCreators(
{ ...ClientActions, ...MapActions, ...CaboActions },
dispatch
);
export default connect(
mapStateToProps,
mapDispatchToProps
)(ViewClient);

Categories

Resources