Resutl showing book is not defined in console - reactjs

I used to show my New arrival page from Home page when i select books. I Planned to show only a book that is selected in Home page book list. But its now showing in New arrival page right now. Please help me to get rid off.
import React from "react";
const BookDetails = (props) => {
console.log(props.book);
if (props.book === null) return <div></div>;
return (
<div>
<h3>{props.book.bookName}</h3>
</div>
);
};
export default BookDetails;
(This is another code i used my onclick fucntion)
import React from "react";
import Book from "../Representational/Book";
import { withRouter } from "react-router-dom";
const ComponentList = (props) => {
return props.books.map((item, index) => {
return (
<Book
bookName={item.bookName}
writer={item.writer}
publish={item.publish}
key={item.id}
selectedBookHandler={()=>props.selectedBookHandler(Book)}
/>
);
});
};
export default withRouter(ComponentList);
(Below are codes as main component)
import { Component } from "react";
import ComponentList from "./Lists/ComponentList";
import BookList from "../Assets/BookList";
import NewBook from "./Representational/NewBook";
import About from './Representational/About';
import {Route, NavLink} from 'react-router-dom';
import BookDetails from "./Representational/BookDetails";
class MainComponent extends Component {
constructor(props){
super(props)
this.state = {
books: BookList,
selectedBook: null
}
}
selectedBookHandler = books=>{
this.setState({
selectedBook: books
})
}
render() {
const newCopy = (
<ComponentList
books={this.state.books}
selectedBookHandler={this.selectedBookHandler}
/>
);
return (
<div className="book-project">
<nav className="nav-bar">
<ul>
<li>
<NavLink to="/" exact>Home</NavLink></li>
<li><NavLink to="/new">New Arrival</NavLink></li>
<li><NavLink to="/about-us">About Us</NavLink></li>
</ul>
</nav>
<div>
<Route path="/" exact render={()=> newCopy} />
<Route path="/new" exact component={NewBook}/>
<Route path="/about-us" exact component= {About}/>
<BookDetails book={this.state.selectedBook}/>
</div>
<div className="head">
<h1 className="appHeading head">New Book List</h1>
</div>
<div className="btn">
<button onClick={this.toggleBook}>Toggle</button>
<input type="text" onChange={this.changeInputState} />
</div>
</div>
);
}
}
export default MainComponent;
Please Help me.

Related

Extract Data from API and show in another page

This question may sound silly to some people, but I am really confused on how to do it
I have 3 file: App.js, HomePage.js and Profile.js
App.js :
import React from "react"
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./components/HomePage";
import Profile from "./components/Profile"
function App() {
return (
<Router>
<Switch>
<Route path="/" exact component={HomePage} />
<Route exact path="/profile/:profileId" component= {Profile} />
</Switch>
</Router>
);
}
export default App;
From here, the default page it will go to is HomePage.js
HomePage.js:
import React, { Component } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
class HomePage extends Component {
constructor() {
super();
this.state = {
userData: [],
}
}
componentDidMount() {
axios.get("XXXXXXXX").then((response) => {
const userDataList = response.data.users;
this.setState({
userData: userDataList
})
})
}
render() {
const userGrid = this.state.userData.map((user, index) => {
return (
<div key={index}>
<Link to={`/profile/${user.id}`}>
<img src={user.profilepicture} />
<p>{user.name}</p>
</Link>
</div>
)
})
return (
<div className="App">
<div className="card">
<div className="card__top">
<span className="card__title">
<p>Select An Account</p>
</span>
</div>
<div className="card__bottom">
<div className="card__table">
{userGrid}
</div>
</div>
</div>
</div>
)
}
}
export default HomePage;
In HomePage.js, I am able to show the profile picture and name of the user from API.
In the next page which is Profile.js , I am able to print the ID of the user.
Profile.js:
import React, { Component } from "react";
class Profile extends Component{
componentDidMount(){
const uid = this.props.match.params.profileId;
}
render() {
console.log(this.props.match);
return(
<h1>{this.props.match.params.profileId}</h1>
)
}
}
export default Profile;
As you can see I am printing the ID of user.
Here I also want to show the Profile Picture of the user which I selected in HomePage.js
This I am not able to do it.
JSON file:
{ - users: [-{id:1, name:"abc", profilepicture: "xxxxx.jpeg"}, ]}
You need to store a global state in your applicattion, which you can access from every connected component. This is a more complex topic. redux is a good framework to handle your global state changes.
Here is a tutorial: https://appdividend.com/2018/06/14/how-to-connect-react-and-redux-with-example/
I found it pretty hard to learn redux, but in the end it takes away a lot of pain. Because this is a problem you gonna have in every app you build with react.
You need use Context API o redux
Example context API: https://ibaslogic.com/react-context-api/
Context's well to little projects, but Redux performs better.
App.js
import React from "react"
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import HomePage from "./components/HomePage";
import Profile from "./components/Profile"
import { UsersProvider } from "./UsersProvider.js";
function App() {
return (
<Router>
<UsersProvider>
<Switch>
<Route path="/" exact component={HomePage} />
<Route exact path="/profile/:profileId" component= {Profile} />
</Switch>
</UsersProvider>
</Router>
);
}
export default App;
UsersContext.js
import React, { Component } from "react"
const UsersContext = React.createContext();
const UsersProvider = UsersContext.Provider;
const UsersConsumer = TodosContext.Consumer;
class MyContext extends Component {
state = {
value: null,
};
setValue = (value) => {
this.setState({ value });
};
render() {
return (
<UsersProvider value={{ setValue, value }}>{this.props.children}
</UsersProvider>
)
}
}
export { UsersContext, UsersProvider, UsersConsumer }
HomePage.js
import React, { Component } from "react";
import axios from 'axios';
class HomePage extends Component {
componentDidMount() {
axios.get("XXXXXXXX").then((response) => {
const userDataList = response.data.users;
// updating your context
this.props.context.setValue(userDataList);
})
}
render() {
const userGrid = this.props.context.value.map((user, index) => {
return (
<div key={index}>
<Link to={`/profile/${user.id}`}>
<img src={user.profilepicture} />
<p>{user.name}</p>
</Link>
</div>
)
})
return (
<div className="App">
<div className="card">
<div className="card__top">
<span className="card__title">
<p>Select An Account</p>
</span>
</div>
<div className="card__bottom">
<div className="card__table">
{userGrid}
</div>
</div>
</div>
</div>
)
}
}
export default HomePage;
Profile.js
import React, { Component } from "react";
import { UsersConsumer } from "./UsersContext.js";
class Profile extends Component{
render() {
return(
<UsersConsumer>
{users => (
<h1>{users.value.find(user => user.id === this.props.match.params.profileId)}</h1>
)}
</UsersConsumer>
)
}
}
export default Profile;

React function will not rerender even if state hook called

In this function:
import React, { useEffect } from 'react';
import { BrowserRouter, Route, Link } from 'react-router-dom'
import HomeScreen from './Screens/HomeScreen'
import './App.css';
import currentStrings from './utils/currentlang'
function App() {
const [currentlang, setCurrentStrings] = React.useState(currentStrings)
return (
<BrowserRouter>
<div className="grid-container">
<header className="header">
<div className="brand">
<Link to="/" >
</Link>
</div>
<div className="header-side">
{currentlang.getCurrent.subtitle}
</div>
<div className="header-right">
<button onClick={() => setCurrentStrings(currentlang.switchLang())}> {currentlang.getCurrent.traduction} </button>
</div>
<div>
</div>
</header>
<main className="main">
<div className="content">
<Route path="/" exact={true} component={HomeScreen} />
</div>
</main>
<footer className="footer">
© 2020
</footer>
</div>
</BrowserRouter>
);
}
export default App;
I use a button (<button onClick={() => setCurrentStrings(currentlang.switchLang())}> ) to change one of the properties of the object currentStrings (or currentLang used for the useState hook)
However it seems my function does not rerender, i can confirm this since my logs do tell the object does change its properties when the button is clicked, but the screen does not show it.
import {strings as frstrings} from '../res/lang/fr/strings'
import {strings as engstrings} from '../res/lang/eng/strings'
class CurentLang {
constructor(){
this.current = engstrings;
}
switchLang() {
if(this.current === frstrings){
this.current = engstrings;
console.log("engstrings");
} else{
this.current = frstrings;
console.log("frstrings");
}
return new this.CurentLang;
}
get getCurrent(){
return this.current;
}
}
var currentStrings = new CurentLang()
export default currentStrings;

How to get rid of this ? from the url

I'm making a react application and whenever I search for something(eg cat) on the homepage, the url changes to search/cat and the forward, backward button work normally & help me switch between the homepage and the cat search page ...but when i search for something again (eg rat) after(homepage->cat) so the url changes to search/rat? and now when i press the back button the url changes to search/rat and i'm on the same page then if i press back button again the url becomes search/cat but the page still has the results of the rat search and if i press back again ,the homepage appears..why is this happening?I think it's because of the ? that appears at the end of the url..Please help
after searching cat
after searching for rat
after pressing the back button
after pressing the back button
after pressing the back button
This is the code of the search bar
import React, { Component } from "react";
import "./styles/searchBar.scss";
import "font-awesome/css/font-awesome.min.css";
import { withRouter } from "react-router-dom";
import SearchForm from "./SearchForm";
import { connect } from "react-redux";
import { fetchRandomPhotos } from "../redux/actions/randomPhotoAction";
class SearchBar extends Component {
state = {
searchQuery: "",
};
componentDidMount() {
this.props.fetchRandomPhotos();
}
handleChange = (event) => {
this.setState({ searchQuery: event.target.value });
};
handleSubmit = (event) => {
//event.preventDefault();
this.props.history.push(`/search/${this.state.searchQuery}`);
};
handleProfile = () => {
this.props.history.push(`/public/${this.props.photo.user.username}`);
};
render() {
const { photo } = this.props;
return !photo ? (
<div className="search-bar-container">
<div className="search-bar-area">
<div className="about-foto-fab">
<h1>Foto-Fab</h1>
<p>The internet's source of freely-usable images.</p>
<p>Powered by creator everywhere</p>
</div>
<SearchForm
onSubmit={this.handleSubmit}
onChange={this.handleChange}
/>
</div>
</div>
) : (
<div
className="search-bar-container"
style={{ backgroundImage: `url("${photo.urls.full}")` }}
>
<div className="black-layer"></div>
<div className="search-bar-area">
<div className="about-foto-fab">
<h1>Foto-Fab</h1>
<p>The internet's source of freely-usable images.</p>
<p>Powered by creator everywhere</p>
</div>
<SearchForm
onSubmit={this.handleSubmit}
onChange={this.handleChange}
/>
</div>
<div className="picture-info">
<div className="photographer">
<p onClick={this.handleProfile}>
<strong>Photo</strong> by {""}
<strong>{photo.user.name}</strong>
</p>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
photo: state.randomPhotoState.photo,
};
};
export default connect(mapStateToProps, { fetchRandomPhotos })(
withRouter(SearchBar)
);
This is the App.js
import React from "react";
import Navbar from "./components/Navbar";
import { BrowserRouter, Switch, Route, Redirect } from "react-router-dom";
import Home from "./pages/Home";
import LoginPage from "./pages/LoginPage";
import ProfilePage from "./pages/ProfilePage";
import SearchPage from "./pages/SearchPage";
import PublicUserProfilePage from "./pages/publicUserProfilePage";
import MobileNavigation from "./components/MobileNavigation";
import AboutPage from "./pages/AboutPage";
function App() {
return (
<BrowserRouter>
<Navbar />
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={LoginPage} />
<Route exact path="/profile" component={ProfilePage} />
<Route exact path="/search/:searchQuery" component={SearchPage} />
<Route exact path="/about" component={AboutPage} />
<Route
exact
path="/public/:username"
component={PublicUserProfilePage}
/>
<Redirect to="/" />
</Switch>
<MobileNavigation />
</BrowserRouter>
);
}
export default App;
search form component
import React, { Component } from "react";
export class SearchForm extends Component {
render() {
const { onSubmit, onChange } = this.props;
return (
<form className="search-form" onSubmit={onSubmit}>
<input
type="text"
placeholder="Search free high-resolution photos"
onChange={onChange}
/>
<button type="submit">
<i className="fa fa-search"></i>
</button>
</form>
);
}
}
export default SearchForm;
import React, { Component } from "react";
import "./styles/searchBar.scss";
import "font-awesome/css/font-awesome.min.css";
import { withRouter } from "react-router-dom";
import SearchForm from "./SearchForm";
import { connect } from "react-redux";
import { fetchRandomPhotos } from "../redux/actions/randomPhotoAction";
class SearchBar extends Component {
state = {
searchQuery: "",
};
componentDidMount() {
this.props.fetchRandomPhotos();
}
handleChange = (event) => {
this.setState({ searchQuery: event.target.value });
};
handleSubmit = (event) => {
event.preventDefault();
if (this.state.searchQuery) {
this.props.history.push(`/search/${this.state.searchQuery}`);
}
};
handleProfile = () => {
this.props.history.push(`/public/${this.props.photo.user.username}`);
};
render() {
const { photo } = this.props;
return !photo ? (
<div className="search-bar-container">
<div className="search-bar-area">
<div className="about-foto-fab">
<h1>Foto-Fab</h1>
<p>The internet's source of freely-usable images.</p>
<p>Powered by creator everywhere</p>
</div>
<SearchForm
onSubmit={this.handleSubmit}
onChange={this.handleChange}
/>
</div>
</div>
) : (
<div
className="search-bar-container"
style={{ backgroundImage: `url("${photo.urls.full}")` }}
>
<div className="black-layer"></div>
<div className="search-bar-area">
<div className="about-foto-fab">
<h1>Foto-Fab</h1>
<p>The internet's source of freely-usable images.</p>
<p>Powered by creator everywhere</p>
</div>
<SearchForm
onSubmit={this.handleSubmit}
onChange={this.handleChange}
/>
</div>
<div className="picture-info">
<div className="photographer">
<p onClick={this.handleProfile}>
<strong>Photo</strong> by {""}
<strong>{photo.user.name}</strong>
</p>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
photo: state.randomPhotoState.photo,
};
};
export default connect(mapStateToProps, { fetchRandomPhotos })(
withRouter(SearchBar)
);

React Context: TypeError: Cannot read property 'areResultsVisible' of undefined

Can someone please help me? I'm trying to pass data through context from one component to another (from Search.js to Container.js). However, I'm getting a type error. I searched many questions in Web, but haven't found an answer. Sorry, if it's childish problem, I'm new.
Search.js:
import React, { Component } from 'react'
import { StyledFormSearchBar } from '../styles'
import { data } from '../data'
const SearchContext = React.createContext()
export default class Search extends Component {
constructor() {
super()
this.state = {
value: '',
results: [],
areResultsVisible: false
}
this.handleSearch = this.handleSearch.bind(this)
}
handleSearch(e) {
this.setState = {
value: e.target.value,
results: data.filter(item => {
return item.title.toLowerCase().includes(e.target.value.toLowerCase())
}),
areResultsVisible: true
}
}
render() {
return (
<StyledFormSearchBar>
<input type="search" name="search" className="border border-dark rounded" onSubmit={this.handleSearch}/>
<button type="submit" value="submit" className="bg-warning border-0 text-danger rounded-right position-relative">
<i className="fas fa-search"></i>
</button>
<SearchContext.Provider value = {{
...this.state,
handleSearch: this.handleSearch
}}>
{this.props.children}
</SearchContext.Provider>
</StyledFormSearchBar>
)
}
}
const SearchContextConsumer = SearchContext.Consumer
export { SearchContextConsumer }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Container.js:
import React from 'react'
import { Route, Switch } from "react-router-dom"
import { StyledDivGridContainer } from './styles'
import { SearchContextConsumer } from './header/Search'
import Carousel from './container/Carousel'
import MobilePhonesDiscount from './container/products/carousel/MobilePhonesDiscount'
import LaptopsDiscount from './container/products/carousel/LaptopsDiscount'
import TabletsDiscount from './container/products/carousel/TabletsDiscount'
import Products from './container/Products'
import SearchResults from './container/SearchResults'
import MobilePhones from './container/products/MobilePhones'
import Laptops from './container/products/Laptops'
import Tablets from './container/products/Tablets'
import ProductPage from './container/ProductPage'
import About from './container/About'
import ContactUs from './container/ContactUs'
export default function Container() {
return (
<StyledDivGridContainer>
<div className="no-gutters justify-content-between">
<SearchContextConsumer>
{
value => {
return (
!value.areResultsVisible
? <Switch>
<Route exact path="/" component={Carousel}/>
<Route exact path="/" component={Products}/>
</Switch>
: <Route exact path="/" component={SearchResults}/>
)
}
}
</SearchContextConsumer>
<Route path="/mobile_phones_discount" component={MobilePhonesDiscount}/>
<Route path="/laptops_discount" component={LaptopsDiscount}/>
<Route path="/tablets_discount" component={TabletsDiscount}/>
<Route path="/mobile_phones" component={MobilePhones}/>
<Route path="/laptops" component={Laptops}/>
<Route path="/tablets" component={Tablets}/>
<Route path="/product_page" component={ProductPage}/>
<Route path="/about" component={About}/>
<Route path="/contact_us" component={ContactUs}/>
</div>
</StyledDivGridContainer>
)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Search.js is in Header.js:
import React, { Component } from 'react'
import { StyledHeader,
StyledSpanAccount } from './styles'
import { Link } from "react-router-dom"
import Catalogue from "./header/Catalogue"
import Search from "./header/Search"
export default class Header extends Component {
render() {
return (
<StyledHeader className="d-flex w-100 bg-light shadow justify-content-center">
<div className="d-flex flex-wrap justify-content-around align-items-center">
<div className="my-1 mr-3">
<Link to="/" className="logo">
<img src={require('../img/logo.webp')} alt="logo" className="img-tumbnail"/>
</Link>
</div>
<Catalogue/>
<Search/>
<div className="d-flex my-3">
<i className="fas fa-shopping-cart"></i>
<i className="fas fa-user-alt ml-3"></i>
<a href="#" className="d-flex flex-nowrap">
<StyledSpanAccount className="ml-2">Log in</StyledSpanAccount>
</a>
<a href="#" className="d-flex flex-nowrap">
<StyledSpanAccount className="ml-2">Sing up</StyledSpanAccount>
</a>
</div>
</div>
</StyledHeader>
)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Container.js is in App.js near Header.js:
import React from 'react';
import { Route } from "react-router-dom";
import { StyledDivWrapper } from './components/styles';
import Header from './components/Header';
import Container from './components/Container';
import Footer from './components/Footer';
export default function App() {
return (
<StyledDivWrapper className="d-flex flex-column">
<Route path="/" component={Header}/>
<Route path="/" component={Container}/>
<Route path="/" component={Footer}/>
</StyledDivWrapper>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Error screenshot
My folder tree
The problem is that your Container component is not within your SearchContext.Provider. To make sure your code works correctly you must have your SearchContext Provider directly inside you App Component so that it is a common parent of both Search and Container component
Firstly, create a context in a different file
// SearchContext.js
export const SearchContext = React.createContext();
const SearchContextConsumer = SearchContext.Consumer
export { SearchContextConsumer }
Secondly, create a component which acts as a provider
// SearchProvider.js
class SearchProvider extends React.Component {
constructor() {
super()
this.state = {
value: '',
results: [],
areResultsVisible: false
}
this.handleSearch = this.handleSearch.bind(this)
}
handleSearch(e) {
this.setState = {
value: e.target.value,
results: data.filter(item => {
return item.title.toLowerCase().includes(e.target.value.toLowerCase())
}),
areResultsVisible: true
}
}
render() {
return (
<SearchContext.Provider value = {{
...this.state,
handleSearch: this.handleSearch
}}>
{this.props.children}
</SearchContext.Provider>
)
}
}
Now you Search Component would simply be
// Search.js
export default class Search extends Component {
render() {
return (
<SearchContext.Consumer>
{({handleSearch}) => (
<StyledFormSearchBar>
<input type="search" name="search" className="border border-dark rounded" onSubmit={handleSearch}/>
<button type="submit" value="submit" className="bg-warning border-0 text-danger rounded-right position-relative">
<i className="fas fa-search"></i>
</button>
</StyledFormSearchBar>
)}
</SearchContext.Consumer>
)
}
}
Also no you can use your SearchProvider in App.js like
export default function App() {
return (
<SearchProvider>
<StyledDivWrapper className="d-flex flex-column">
<Route path="/" component={Header}/>
<Route path="/" component={Container}/>
<Route path="/" component={Footer}/>
</StyledDivWrapper>
</SearchProvider>
);
}
You first need to wrap your top level component with the context provider (Search), because the point of the context api is to pass the data top-down without having to explicitly pass it through every level, otherwise the context consumer won't have any context to consume in first place:
<Search>
<App />
</Search>
Also, you need to use the prop value to pass the context from the provider, and not any prop (like searchValue in your code):
<SearchContext.Provider value = {{
...this.state,
handleSearch: this.handleSearch
}}>
{this.props.children}
</SearchContext.Provider>
Import createContext like
import { React, createContext } from 'react';
export const MyContext = createContext();
this helped me.

Not able to get the value after updating the state

I have an application which has 3 pages .home ,shop,about.I want to add authentication to only page ie shop. When the user want to go to the shop page he has to login then only the user will go the shop page. I am maintaining a global state which has intital value isLogin:False. I extracted this value through mapStatetoProps in my App.js where all my Routes are there.For /shop path i am using the value as ternary condition. Initially the value (isLogin) is false it will render the Login page upon clicking shop link. But after proper authentication i am unable to redirect to the shop page
//App.js
import React ,{Component} from 'react';
import './App.css';
import Navigation from './Step1/Navbar'
import Home from './Step1/Home'
import Shop from './Step1/Shop'
import About from './Step1/About'
import Login from './LoginAuthentication/Loginform'
import {BrowserRouter as Router,Route} from 'react-router-dom'
import {connect} from 'react-redux'
const mapStateToProps=(state)=>{
console.log(state)
return{
isLogin:state.isLogin
}
}
class App extends Component {
render(){
return (
<Router>
<div className="App">
<Navigation/>
<Route path="/" exact component={Home}/>
<Route path="/about" component={About}/>
<Route path="/shop"
render={({isLogin}) =>(
isLogin ? <Shop/> : <Login/>
) }
/>
</div>
</Router>
);
}
}
export default connect(mapStateToProps,null)(App);
//Navigation
import React from 'react'
import {NavLink} from 'react-router-dom'
const Navbar=()=> {
return (
<div>
<nav className="navbar navbar-expand-sm bg-dark">
<ul className="navbar-nav">
<li className="nav-item"><NavLink to="/" >Home</NavLink> </li>
<li className="nav-item"><NavLink to="/shop">Shop </NavLink> </li>
<li className="nav-item"><NavLink to ="/About">About </NavLink> </li>
<li className="nav-item"><NavLink to ="/page">Page </NavLink> </li>
</ul>
</nav>
</div>
)
}
export default Navbar
// LoginForm.js
import React, { Component } from 'react'
import {connect} from 'react-redux'
import {withRouter} from 'react-router-dom'
//import {Redirect} from 'react-router-dom'
import {action1} from '../Actions/action1'
const mapDispatchToProps=(dispatch)=>{
return{
LoginCheck:()=>dispatch(action1())
}
}
class Loginform extends Component {
state={
username:'',
password:'',
uname:'dharmendra',
pwd:'230498'
}
nameHandler=(event)=>{
if(event.target.name==='UserName'){
this.setState({username:event.target.value})
}
if(event.target.name==='Password'){
this.setState({password:event.target.value})
}
}
submitHandler=(event,state)=>{
event.preventDefault()
const uname=this.state.uname
const pwd=this.state.pwd
if(this.state.username===uname && this.state.password===pwd){
this.props.LoginCheck()
//return <Redirect to="/shop"/>
//this.props.history.push("/shop")
this.props.history.push("/page");
console.log('hi i am in shop page successful')
}
else{
alert("Enter proper Credentials")
}
}
render() {
return (
<div className="login">
<form onSubmit={this.submitHandler}>
<div className="form-group">
<h1>
<input
type="text"
placeholder="UserName"
value={this.state.username}
onChange={this.nameHandler}
className="form-control"
name="UserName"
/>
</h1>
</div>
<br></br>
<div className="form-group">
<h1>
<input
type="password"
placeholder="Password"
value={this.state.password}
onChange={this.nameHandler}
className="form-control"
name="Password"
/>
</h1>
</div>
<br></br>
<div className="form-group">
<button type="submit" className="btn btn-success" >Login</button>
</div>
</form>
</div>
)
}
}
export default withRouter(connect(null,mapDispatchToProps)(Loginform))
//reducer1.js
import {LOGINCHECK} from '../Constants/actiontypes'
const initialState={
isLogin:false
}
const reducer1=(state=initialState,action)=>{
//console.log(action.type)
//console.log(state)
if(action.type===LOGINCHECK){
return Object.assign({},state,{isLogin:true})
}
return state
}
export default reducer1
//action.js
import {LOGINCHECK} from '../Constants/actiontypes'
export const action1 =()=>{
return{
type:LOGINCHECK
}
}
Unable to redirect to the shop page even after proper authentication also
Change the route like this :
<Route path="/shop"
render={() =>(
this.props.isLogin ? <Shop/> : <Login/>
) }
/>
The props that are passed to the render prop in the Route components are route props, not the App component props (they don't contain isLogin)
https://reacttraining.com/react-router/web/api/Route/route-props

Resources