I am using React.js but I don't achieve to switch modal. Here is my code :
import React from "react";
import ReactDOM from "react-dom";
import moment from "moment";
import { Modal, version, Button } from "antd";
import "antd/dist/antd.css";
import { BrowserRouter, Link, Redirect, Route, Switch } from "react-router-dom";
import Clickthere from "Clickthere";
class App extends React.Component {
state = { visible: false };
showModal = () => {
this.setState({
visible: true
});
};
handleOk = (e) => {
console.log(e);
this.setState({
visible: false
});
};
handleCancel = (e) => {
console.log(e);
this.setState({
visible: false
});
};
render() {
return (
(
<div>
<Button type="primary" onClick={this.showModal}>
Open
</Button>
<Modal
title="Basic Modal"
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
>
<p>Some contents...</p>
<p>Some contents...</p>
<p>Some contents...</p>
<p style={{ textAlign: "center" }}>
Other thing?{" "}
<BrowserRouter>
<Link to="/clickthere">
<i className="fas fa-user-plus" /> Click there
</Link>
</BrowserRouter>
</p>
</Modal>
</div>
),
(
<BrowserRouter>
<Switch>
<Route path="/clickthere" component={Clickthere} />
</Switch>
</BrowserRouter>
)
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
I achieve to open the first modal but I don't achieve when I click on "Click there" nothing happen...
Here is the code of the component Clickthere :
import { Modal } from "react-bootstrap";
import React from "react";
import { BrowserRouter, Switch } from "react-router-dom";
const Clickthere = (props) => {
console.log(props);
return (
<>
<Modal>
<div>
<p>This is a test.</p>
</div>
</Modal>
<BrowserRouter>
<Switch></Switch>
</BrowserRouter>
</>
);
};
export default Clickthere;
Do you know why it does not work ?
Thank you very much !
Here is my code : My code
Related
I have some user components on which I used the navigation component and I am routing two components on it. when I click on the Device.js component button it should remove device.js and it should redirect to the Keyregister.js component which is having navigation component in it .It should change the value according to the props sent to it. But it is not happening.
user.js
import React from "react";
import { Route, Switch } from "react-router";
import "./User.css";
import Navigation from "./Dashboard/Navigation";
import AuthModel from "./Dashboard/AuthModel";
import DeviceDetails from "./Dashboard/DeviceDetails";
function User() {
return (
<>
<Navigation
link1={""}
link2={"Authmodel"}
link3={"Requests"}
link1name={"Key Status"}
link2name={"Key Upload"}
link3name={"KEY DOWNLOAD"}
/>
<Switch>
<Route path="/User/Dashboard/AuthModel" component={AuthModel} />
<Route path="/User/Dashboard/DeviceDetails" component={DeviceDetails} />
</Switch>
</>
);
}
export default User;
Navigation.js
import React from "react";
import "./Navigation.css";
import { Link } from "react-router-dom";
import { useHistory } from "react-router";
import { Image } from "react-bootstrap";
import EvoVert from "../../../Resources/EvoluteVert.png";
function Navigation(props) {
const history = useHistory();
const handleLogout = (e) => {
e.preventDefault();
localStorage.removeItem("accessToken");
localStorage.removeItem("roleType");
history.push("/");
};
return (
<>
<main classMain="main">
<aside className="sidebar ">
<Image className="Evo-logo" src={EvoVert} />
<nav className="nav">
<ul style={{ textDecoration: "none" }}>
<li>
<Link to={`/User/Dashboard/${props.link2}`}>
{props.link2name}
</Link>
</li>
<li>
<Link to={`/User/Dashboard/${props.link1}`}>
{props.link1name}
</Link>
</li>
<li>
<Link to={`/User/Dashboard/${props.link3}`}>
{props.link3name}
</Link>
</li>
</ul>
</nav>
</aside>
</main>
</>
);
}
export default Navigation;
Device.js
import React, { useState, useEffect } from "react";
import { Form } from "react-bootstrap";
import "./Dashboard.css";
import { useHistory } from "react-router";
import KeyRegister from "./KeyRegister";
function DeviceDetails() {
const history = useHistory();
const [visible, setvisible] = useState(true);
const [serialNum, setSerialNum] = useState("");
const [slot, setSlot] = useState("");
const frmsubmit = (e) => {};
return (
<>
<section className="device-Details_Dashboard">
<div className="container">
<div
className="heading"
style={{
color: "#312450",
fontWeight: "400",
fontSize: "35px",
padding: "1rem",
}}
>
DEVICE DETAILS
</div>
<Form onSubmit={frmsubmit}>
<div>
<div className="device-details-box">
<label>Serial Number</label>
<br />
<input
type="text"
value={serialNum}
onChange={(e) => setSerialNum(e.target.value)}
/>
</div>
<div className="device-details-box">
<label>Slot Number</label>
<br />
<input
type="text"
value={slot}
onChange={(e) => setSlot(e.target.value)}
/>
</div>
</div>
<button className="devDetSub" onClick={frmsubmit}>
<span>SUBMIT</span>
</button>
</Form>
</div>
</section>
{visible && <KeyRegister />}
</>
);
}
export default DeviceDetails;
KeyRegister.js
import React, { useState, useEffect } from "react";
import "./Navigation.css";
import { Route, Switch } from "react-router";
import DUPKT from "./DUPKT";
import MasterSession from "./MasterSession";
import AES from "./AES";
import Navigation from "./Navigation";
function KeyRegister() {
return (
<>
<Navigation
link1={"DUPKT"}
link2={"MasterSession"}
link3={"AES"}
link1name={"DUPKT"}
link2name={"MASTER KEY"}
link3name={"AES"}
/>
<main classMain="main">
<Switch>
<Route path="/User/Dashboard/DUPKT" component={DUPKT} exact />
<Route
path="/User/Dashboard/MasterSession"
component={MasterSession}
exact
/>
<Route path="/User/Dashboard/AES" component={AES} exact />
</Switch>
</main>
</>
);
}
export default KeyRegister;
I cannot see anywhere in your naviagation component props you are passing device details.
<Navigation
link1={""}
link2={"Authmodel"}
link3={"Requests"}
link1name={"Key Status"}
link2name={"Key Upload"}
link3name={"KEY DOWNLOAD"} //should have device details in props
/>
So I have a series of code where a button in the Header.jsx file that if clicked, it will display the content of the Notification.jsx file. The problem here is, I don't exactly know how can I display the content of Notification.jsx in index.js. I tried using conditional statements and is it possible to hide the h1 element once the button is clicked?
Header.jsx
import React from "react";
import { Button } from "#mui/material";
import { IconButton } from "#mui/material";
import NotificationsIcon from "#mui/icons-material/Notifications";
import SearchIcon from "#mui/icons-material/Search";
import Menu from "#mui/material/Menu";
import MenuItem from "#mui/material/MenuItem";
import FullNotifList from "./FullNotifList"
export default function Header() {
const [anchorEl, setAnchorEl] = React.useState(null);
const open = Boolean(anchorEl);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
<div>
<Button
id="basic-button"
aria-controls={open ? "basic-menu" : undefined}
aria-haspopup="true"
aria-expanded={open ? "true" : undefined}
onClick={handleClick}
>
<IconButton>
<NotificationsIcon />
</IconButton>
</Button>
<Menu
id="basic-menu"
anchorEl={anchorEl}
open={open}
onClose={handleClose}
MenuListProps={{
"aria-labelledby": "basic-button",
}}
>
{/* Button needs to be clicked in order to display Notification.jsx */}
<Button variant="contained">Notification Center</Button>
<MenuItem onClick={handleClose}>Profile</MenuItem>
<MenuItem onClick={handleClose}>My account</MenuItem>
<MenuItem onClick={handleClose}>Logout</MenuItem>
</Menu>
<IconButton>
<SearchIcon />
</IconButton>
</div>
);
}
Notification.jsx
import React from "react";
export default function Notification(){
return(
<div>
<ul>
<li> Hello </li>
<li> Hello </li>
<li> Hello </li>
<li> Hello </li>
</ul>
</div>
)
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';
import Header from './Header'
import './index.css'
import Footer from './Footer';
import Notification from './Notification';
export default function Page(props) {
const [isClicked, setIsClicked] = React.useState(false)
function showHide(e) {
setIsClicked(true)
};
return(
<div className='main'>
<Header onClick={showHide}/>
{isClicked && <Notification />}
<h1> Sample body </h1>
<Footer />
</div>
)
}
ReactDOM.render(
<Page />,
document.getElementById('root')
);
Here is the sandbox link: https://codesandbox.io/s/friendly-darkness-9u5s22?file=/src/index.js
You just need to create a state property to handle if the element is visible or not (ex: showNotification ) defaulting to false:
const [showNotification, setShowNotification] = React.useState(false);
Then using the button click event to set it to true
<Button variant="contained" onClick={()=>{setShowNotification(true)}}>Notification Center</Button>
Then you implement conditional rendering by using the && operator inside JSX for the return, something like :
{showNotification && <Notification />}
The problem is that your Header component doesn't have prop onClick, so nothing is executing.
i'm trying to clone amazone website i'm following (celever programmer on youtube)
so i wanted to create amazon basket with React context api this error occurs "Error: Objects are not valid as a React child (found: object with keys {map, forEach, count, toArray, only}). If you meant to render a collection of children, use an array instead."
Here is my code
index.js :
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { StateProvider } from "./StateProvider";
import reducer, { initialState } from "./reducer";
ReactDOM.render(
<React.StrictMode>
<StateProvider initialState={initialState} reducer={reducer}>
<App />
</StateProvider>
</React.StrictMode>,
document.getElementById("root")
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
serviceWorker.unregister();
stateProvider.js:
import React, { createContext, useContext, useReducer } from "react";
import { Children } from "react";
export const StateContext = createContext();
export const StateProvider = ({ reducer, initialState, children }) => (
<StateContext.Provider value={useReducer(reducer, initialState)}>
{Children}
</StateContext.Provider>
);
export const useStateValue = () => useContext(StateContext);
reducer.js:
export const initialState = {
basket: [],
};
function reducer(state, action) {
switch (action.type) {
case "ADD_TO__BASKET":
break;
case "REMOVE_FROM_BASKET":
break;
default:
return state;
}
}
export default reducer;
header.js:
import React from "react";
import "./Header.css";
import { Link } from "react-router-dom";
import SearchIcon from "#material-ui/icons/Search";
import { grey } from "#material-ui/core/colors";
import ShoppingBasketIcon from "#material-ui/icons/ShoppingBasket";
import { useStateValue } from "./StateProvider";
function Header() {
const [{ basket }] = useStateValue();
return (
<nav className="header">
{/* logo */}
<Link to="/">
<img
className="header__logo"
src="https://www.mabaya.com/wp-content/uploads/2019/10/amazon_PNG25.png"
alt=""
/>
</Link>
{/* SearchBox */}
<div className="header__search">
<input type="text" className="header__SearchBox" />
<SearchIcon className="header__SearchIcon" />
</div>
{/* Links */}
<div className="header__nav">
{/* 1link */}
<Link to="/login" className="header__link">
<div className="header__option">
<span className="header__optionsecondary">Hello,</span>
<span>Sign in</span>
</div>
</Link>
{/* 2link */}
<Link to="/check" className="header__link">
<div className="header__option">
<span className="header__optionsecondary">returns </span>
<span>& orders</span>
</div>
</Link>
{/* 3link */}
<Link to="/" className="header__link">
<div className="header__option">
<span className="header__optionsecondary">Your</span>
<span>Prime</span>
</div>
</Link>
{/* basket link */}
<Link to="/check" className="header__link">
<div className="header__optionbasket">
{/* shopping Basket Icon */}
<ShoppingBasketIcon style={{ color: grey[50] }} />
{/* Number of items in the basket */}
<span className="header__optionbaskettext"> {basket.length}</span>
</div>
</Link>
</div>
{/* panier */}
</nav>
);
}
export default Header;
App.js:
import "./App.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import Header from "./Header";
import Home from "./Home";
import Login from "./Login";
function App() {
return (
<Router>
<div className="app">
<Switch>
<Route path="/login">
<Header />
<Login />
</Route>
<Route path="/check">
<Header />
<h1>check guys</h1>
</Route>
<Route path="/">
<Header />
<Home />
</Route>
</Switch>
</div>
</Router>
);
}
export default App;
Thank you in advance for your answer.
I am passing in the state - IsLoggedIn from the App component to the Header component. But, whenever the onClick event triggers, the IsLoggedIn should change it's state. But, this does not seem to be happening. I don't know why this keeps on happening? Does the App component re render itself with the isLoggedIn being false everytime?
App.js
import React, { Component } from 'react';
import { BrowserRouter, Route, Link } from "react-router-dom";
import Header from './Header';
import DashBoard from './Dashboard';
import Home from './Home';
class App extends Component {
constructor() {
super();
this.state = {
isLoggedIn: false
}
}
onEventClick = () => {
if (this.state.isLoggedIn) {
this.setState({isLoggedIn: false});
}
else {
this.setState({isLoggedIn: true});
}
}
render() {
return (
<BrowserRouter>
<div className="container">
<Header onEventClick={this.onEventClick} LoggedInState={this.state.isLoggedIn}/>
<Route path="/" exact={true} component={Home}/>
<Route path="/dashboard" exact={true} component={DashBoard}/>
</div>
</BrowserRouter>
)
}
}
export default App;
Header.js
import React, { Component } from 'react';
import { Link } from "react-router-dom";
class Header extends Component {
constructor(props) {
super(props);
}
renderContent() {
if (this.props.LoggedInState) {
return (
<li>
<a onClick={this.props.onEventClick} href="/api/logout" style={{borderRadius: '12px'}} className="waves-effect waves-light btn-small green darken-1">
Log Out
</a>
</li>
);
}
else {
return (
<li>
<a href="/auth/spotify" onClick={this.props.onEventClick} style={{borderRadius: '12px'}} className="waves-effect waves-light btn green darken-1">
Log in with Spotify
</a>
</li>
);
}
}
render() {
return (
<nav>
<div className="nav-wrapper blue-grey darken-4" style={{paddingLeft: '4px'}}>
<Link to={this.props.LoggedInState ? '/dashboard' : '/'} className="brand-logo">TuneIn</Link>
<ul className="right">
{this.renderContent()}
</ul>
</div>
</nav>
);
}
}
export default Header;
The reason why your state is not updating is that you have an anchor tag which after clicking on it causes the page to reload to the next page, therefore, your state resets back to the default false. Do this instead.
In your header.js
import React, { Component } from "react";
import { Link } from "react-router-dom";
class Header extends Component {
constructor(props) {
super(props);
}
renderContent() {
if (this.props.LoggedInState) {
return (
<li>
<Link
to="/api/logout"
onClick={this.props.onEventClick}
style={{ borderRadius: "12px" }}
className="waves-effect waves-light btn-small green darken-1"
>
Log Out
</Link>
</li>
);
} else {
return (
<li>
<Link
to="/auth/spotify"
onClick={this.props.onEventClick}
style={{ borderRadius: "12px" }}
className="waves-effect waves-light btn green darken-1"
>
Log in with Spotify
</Link>
</li>
);
}
}
render() {
return (
<nav>
<div
className="nav-wrapper blue-grey darken-4"
style={{ paddingLeft: "4px" }}
>
<Link
to={this.props.LoggedInState ? "/dashboard" : "/"}
className="brand-logo"
>
TuneIn
</Link>
<ul className="right">{this.renderContent()}</ul>
</div>
</nav>
);
}
}
export default Header;
Alternatively, if you want to keep your header.js unchanged, you could use local storage as a check to update your state accordingly. In your app.js you can do this
import React, { Component } from "react";
import { BrowserRouter, Route } from "react-router-dom";
import Header from "./components/Header";
import DashBoard from "./components/Dashboard";
import Home from "./components/Home";
class App extends Component {
constructor() {
super();
this.state = {
isLoggedIn: localStorage.getItem("isloggedIn") || false,
};
}
onEventClick = () => {
const isLogged = localStorage.setItem("isloggedIn", true);
if (this.state.isLoggedIn === false) {
this.setState({ isLoggedIn: true });
} else {
localStorage.removeItem("isloggedIn");
this.setState({ isLoggedIn: false });
}
};
render() {
return (
<BrowserRouter>
<div className="container">
<Header
onEventClick={this.onEventClick}
LoggedInState={this.state.isLoggedIn}
/>
<Route path="/" exact={true} component={Home} />
<Route path="/dashboard" exact={true} component={DashBoard} />
</div>
</BrowserRouter>
);
}
}
export default App;
I am not able to update my comment on the page.
After submiting it is showing comment object in the console log but not on the page Console log image
here is my comment.js
import {COMMENTS} from '../shared/comments';
import * as ActionType from './ActionTypes';
export const Comments=(state=COMMENTS ,action) => {
switch(action.type){
case ActionType.ADD_COMMENT:
var comment = action.payload;
comment.id = state.length;
comment.date = new Date().toISOString();
console.log("Comment: ", comment);
return state.concat(comment);
default:
return state;
};
}
here in my store
import {createStore, combineReducers} from 'redux';
import {Dishes} from './dishes';
import {Comments} from './comments';
import {Leaders} from './leaders';
import {Promotions} from './promotions';
export const ConfigureStore=() =>{
const store=createStore(
combineReducers({
dishes:Dishes,
comments:Comments,
leaders:Leaders,
promotions:Promotions
})
);
return store;
};
here is my action creator
import * as ActionTypes from './ActionTypes';
export const addComment=(dishID,rating,author,comment) => ({
type:ActionTypes.ADD_COMMENT,
payload:{
dishID:dishID,
rating:rating,
author:author,
comment:comment,
}
});
here is my App.js
import React from 'react';
import Main from './components/MainComponent';
import './App.css';
import {BrowserRouter} from 'react-router-dom';
import {Provider} from 'react-redux';
import {ConfigureStore} from './redux/configureStore';
const store=ConfigureStore();
class App extends React.Component {
render()
{
return (
<Provider store={store}>
<BrowserRouter>
<div>
<Main/>
</div>
</BrowserRouter>
</Provider>
);
}
}
export default App;
here is my MainComponent.js
import React from 'react';
import Menu from './MenuComponent';
import DishDetail from './DishdetailComponent';
import Home from './HomeComponent';
import Header from './HeaderComponent';
import Footer from './FooterComponent';
import Contact from './ContactComponent';
import About from './AboutComponent';
import {Switch , Route , Redirect,withRouter } from 'react-router-dom';
import {connect} from 'react-redux';
import {addComment} from '../redux/ActionCreators'
const mapStateToProps=state =>{
return{
dishes:state.dishes,
leaders:state.leaders,
comments:state.comments,
promotions:state.promotions
}
};
const mapDispatchToProps = dispatch => ({
addComment:(dishId,rating,author,comment) => dispatch(addComment(dishId,rating,author,comment))
});
class Main extends React.Component {
render()
{
const HomePage=() => {
return(<Home dish={this.props.dishes.filter((dish) => dish.featured)[0]}
leader={this.props.leaders.filter((leader) => leader.featured)[0]}
promotion={this.props.promotions.filter((promo) => promo.featured)[0]} />);
}
const DishWithId=({match}) => {
return(
<DishDetail dish={this.props.dishes.filter((dish) => dish.id === parseInt(match.params.dishId,10))[0]}
comments={this.props.comments.filter(comment => comment.dishId === parseInt(match.params.dishId,10))}
addComment={this.props.addComment} />
);
};
return (
<div>
<Header/>
<Switch>
<Route path="/home" component={HomePage}/>
<Route exact path="/aboutus" component={() => <About leaders={this.props.leaders}/>}/>
<Route exact path="/menu" component={() => <Menu dishes={this.props.dishes}/>} />
<Route path="/menu/:dishId" component={DishWithId} />
<Route exact path="/contactus" component={() => <Contact/>}/>
<Redirect to="/home"/>
</Switch>
<Footer/>
</div>
);
}
}
export default withRouter(connect(mapStateToProps,mapDispatchToProps)(Main));
here is my dishdetail.js component
import React from 'react';
import '../App.css';
import { Card, CardImg, CardBody, CardTitle, CardText ,Breadcrumb ,BreadcrumbItem ,Button, Modal, ModalHeader, ModalBody, Label,Row} from 'reactstrap';
import { LocalForm, Control,Errors } from 'react-redux-form';
import {Link} from 'react-router-dom';
const maxLength=(len) => (val) => !(val) || (val.length <= len);
const minLength=(len) => (val) => (val) && (val.length >= len);
class CommentForm extends React.Component
{
constructor(props)
{
super(props);
this.state={
isModalOpen:false
};
this.toggleModal=this.toggleModal.bind(this);
this.handelSubmit=this.handelSubmit.bind(this);
}
toggleModal()
{
this.setState({
isModalOpen: !this.state.isModalOpen
});
}
handelSubmit(values)
{
this.props.addComment(this.props.dishId,values.rating,values.author,values.comment);
this.toggleModal();
}
render(){
return(
<React.Fragment>
<Button outline onClick={this.toggleModal}><span className="fa fa-pencil"></span>{' '}Submit Comment</Button>
{/*--Modal For Comment--*/}
<Modal id="commentModal" isOpen={this.state.isModalOpen} toggle={this.toggleModal}>
<ModalHeader toggle={this.toggleModal}>Submit Comment</ModalHeader>
<ModalBody>
<LocalForm onSubmit={(values) => this.handelSubmit(values)} >
<Row className="form-row mt-2">
<Label htmlFor="rating">Rating</Label>
<Control.select model=".rating"
id="rating"
name="rating"
className="form-control"
>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</Control.select>
</Row>
<Row className="form-row mt-2">
<Label htmlFor="author">Your Name</Label>
<Control.text model=".author"
id="author"
name="author"
className="form-control"
placeholder="Your Name"
validators={{
minLength:minLength(3),
maxLength:maxLength(15)
}}
/>
<Errors
className="text-danger"
model=".author"
show="touched"
messages={{
minLength:'Must be greater than 2 characters',
maxLength:'Must be 15 characters or less'
}}/>
</Row>
<Row className="form-row mt-2">
<Label htmlFor="comment">Comment</Label>
<Control.textarea model=".comment"
rows="6"
id="comment"
name="comment"
className="form-control"
/>
</Row>
<Row className="form-row mt-2">
<Button type="submit" color="primary" >Submit</Button>
</Row>
</LocalForm>
</ModalBody>
</Modal>
</React.Fragment>
);
}
}
function RenderDish({dish})
{
return(
<div className="col-12 col-md-5 m-1">
<Card>
<CardImg width="100%" src={dish.image} alt={dish.name} />
<CardBody>
<CardTitle><strong>{dish.name}</strong></CardTitle>
<CardText>{dish.description}</CardText>
</CardBody>
</Card>
</div>
);
}
function RenderComments({comments,dishId,addComment})
{
if(comments!=null)
{
return(
<div className="col-12 col-md-5 m-1">
<h4>comments</h4>
<ul className="list-unstyled">
{comments.map(comment => {
return(
<li key={comment.id}>
<p>{comment.comment}</p>
<p>--{comment.author} ,{new Intl.DateTimeFormat('en-US',{year:'numeric',month:'short',day:'2-digit'}).format(new Date(Date.parse(comment.date)))}</p>
</li>
);
})}
</ul>
<CommentForm dishId={dishId} addComment={addComment}/>
</div>
);
}
else{
return <div></div>
}
}
function DishDetail(props)
{
if(props.dish!=null)
{
return(
<div className="container">
<div className="row">
<Breadcrumb >
<BreadcrumbItem><Link to="/home">Home</Link></BreadcrumbItem>
<BreadcrumbItem><Link to="/menu">Menu</Link></BreadcrumbItem>
<BreadcrumbItem>{props.dish.name}</BreadcrumbItem>
</Breadcrumb>
<div className="col-12">
<h3>{props.dish.name}</h3>
<hr/>
</div>
</div>
<div className="row">
<RenderDish dish={props.dish}/>
<RenderComments comments={props.comments} dishId={props.dish.id} addComment={props.addComment}/>
</div>
</div>
);
}
else
{
return(
<div></div>
);
}
}
export default DishDetail;
please help !!