React JS authentication - html

Im new to react js. I am having trouble understanding how to use store. Can anyone help me with the very basic way to create login and handle redirects?
Im creating a simple 2 page application. I want the user to redirect to login page if he is not authorized. Also if anyone has a link to good tutorials for react js kindly share.
index.js
import React, { Component } from 'react'
import ReactDOM from 'react-dom';
import './index.css';
strong text
import Create from "./components/createshipment";
import App from './App';
import {BrowserRouter as Router} from 'react-router-dom';
import {Switch, Redirect} from 'react-router-dom';
import Route from 'react-router-dom/Route';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<Router>
<div className="App">
<Switch>
<Route path="/login" exact strict component={App} />
<Route path="/cs" component={Create} />
</Switch >
</div>
</Router>,
document.getElementById('root')
);
registerServiceWorker();
App.js
import React, { Component } from 'react';
import Login from "./components/login";
import "./components/App.css";
class App extends Component {
constructor(props){
super(props);
// this.onHandle = this.onHandle.bind(this);
}
state={
logged:false,
}
onHandle =(e)=>{
return this.setState({ logged: e});
}
render() {
return (
<div >
<Login logged={this.state.logged} onHandle={e=>this.onHandle(e)} />
</div>
);
}
}
export default App;
Login.js
import React, { Component } from 'react';
import './App.css';
// import er from "./error.png";
import Create from "./createshipment";
import { Route, Link, Switch, Redirect } from 'react-router-dom';
class Login extends React.Component {
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
state={
username:"",
password:"",
flag: false,
showResults:false,
}
isLoggedIn(){
// console.log(Login.flag);
return this.state.flag;
}
onChange =(e)=>{
return this.setState({
[e.target.name]: e.target.value,
});
}
onSubmit = async (event) =>{
// debugger;
event.preventDefault();
const { username, password,flag} = this.state;
this.setState({ flag: false });
if (!(username === 'george' && password === 'george')) {
this.username="";
this.password="";
alert('Invalid username/password');
return false;
}
else{
console.log("abc")
this.props.onHandle(true);
return true;
}
}
render() {
if (this.props.logged === true) {
return <Redirect to='/cs'/>
}
// <div className="errormain">
// { this.state.showResults ? <label className="ErrorMsg"> Invalid Login Details</label> : null }
// </div>
return (
<div className="App">
<form className="frame" >
<h1 className="App-title">ALPHA</h1>
<h2 className="App-para"> Aid Tracking Portal</h2>
<br/><br/> <br/>
<br/><br/><br/>
<br/><br/><br/> <br/>
<br/><br/>
<input required="required" placeholder= "Username" className="lmain" name="username" placeholders='Email' onChange={e=> this.onChange(e)} value={this.state.username}/>
<br/>
<input type="text" required placeholder= "Password" className="lmain" name="password" placeholders='Password' type='password' onChange={e=> this.onChange(e)} value={this.state.password}/>
<button className="LB" value="true" onClick={this.onSubmit} > Login</button>
</form>
</div>
);
}
}
export default Login
CreateShipment.js
import React, { Component } from 'react';
// import logo from '/home/zubair/Desktop/projectmanager/src/logo.svg';
import NewShipment from './form/NewShipment.js';
import Navigation from './navigation';
import './form/createshipment.css';
class Createshipment extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div >
<header className="App-header">
<h1 className="App-title2">Aid Tracker</h1>
<Navigation/>
</header>
<br/><br/>
<NewShipment />
</div>
);
}
}
export default Createshipment;

On web you can use LocalStorage to store data.If you plan to use Redux then I would suggest github.com/rt2zz/redux-persist.

Related

Trouble Getting Class to Render in App.js

I am having some trouble trying to get this clock component to render in my App.js. My App.js looks like this:
function App(){
return (
<div>
<Header/>
<h1>
...
</h1>
<Footer/>
</div>
);
}
export default App;
I would like to get this clock to display a constantly updating time which it does on its own. I am not sure how to call it from App.js without running into DOM or root errors. Any advice would be appreciated!
import ReactDOM from 'react-dom';
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h2>It is {this.state.date.toUTCString()}</h2>
</div>
);
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Clock />);
You reference the Clock component from your App component, as below.
The App component is what you render to the actual DOM.
Sandbox: https://codesandbox.io/s/reverent-jang-63jq5p
Clock.js
import * as React from "react";
export class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerID = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h2>It is {this.state.date.toUTCString()}</h2>
</div>
);
}
}
App.js
import "./styles.css";
import { Clock } from "./Clock";
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Clock />
</div>
);
}
index.js
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
const rootElement = document.getElementById("root");
const root = createRoot(rootElement);
root.render(
<StrictMode>
<App />
</StrictMode>
);

How can I display more than one component from the same file in the App.js?

I am learning React.js. I need to know how can I display more than one component in App.js. I have 2 pages which are Home.js and About.js.
After run the code Just click on About us then you will get only About Page text. But I have About Team and About content too in the About.js file. That is not displaying. I import the
import { About, AboutTeam, AboutContent } from "./Pages/About";
but never use till now because I don't know where should I add AboutTeam, AboutContent. Please check my App.js file. I just need when the user clicks on About us then It will display all the components which I have in About.js.
I added example here https://codesandbox.io/s/happy-almeida-t6q7w?file=/src/App.js
I am getting
This is my expected output
One more doubt, I am using the below code so is this code is the correct way to use?
Would you help me out with this?
Home.js
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './css/Style.css';
const Home=()=>{
return(
<div className="">
<h2>Home page</h2>
</div>
);
}
export default Home;
About.js
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './css/Style.css';
const About=()=>{
return(
<div className="">
<h2>About page</h2>
</div>
);
}
const AboutTeam = () => {
return (
<div className="">
<h2>About Team dummy text</h2>
</div>
);
};
const AboutContent = () => {
return (
<div className="">
<h2>About content dummy text</h2>
</div>
);
};
export { About, AboutTeam, AboutContent };
App.js
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './css/Style.css';
import HeaderMenu from './components/Header';
import Home from './pages/Home';
import { About, AboutTeam, AboutContent } from "./Pages/About";
import Footer from './components/Footer';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
const App=()=>{
return(
<BrowserRouter>
<HeaderMenu />
<div className="">
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={About} />
</Switch>
</div>
<Footer />
</BrowserRouter>
);
}
export default App;
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />,document.getElementById('root'));
serviceWorker.unregister();
You can write in App.js
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './css/Style.css';
import HeaderMenu from './components/Header';
import Home from './pages/Home';
import { About, AboutTeam, AboutContent } from "./Pages/About";
import Footer from './components/Footer';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
const AboutPage = () => (
<>
<About />
<AboutTeam />
<AboutContent />
</>
);
const App=()=>{
return(
<BrowserRouter>
<HeaderMenu />
<Switch>
<Route path="/" exact component={Home} />
<Route path="/about" component={AboutPage} />
</Switch>
<Footer />
</BrowserRouter>
);
}
export default App;
// About.js
const AboutTeam = () => {
return (
<div className="">
<h2>About Team</h2>
</div>
);
};
const About = () => {
return (
<div className="">
<h2>About page</h2>
</div>
);
};
export { About, AboutTeam };
Then import it as
import { About, AboutTeam } from './About.js'
you can create more than one component in one file like this:
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './css/Style.css';
export const AboutTeam =() => {
return (
<div>About Team Page </div>
)
}
export const About =()=>{
return(
<div className="">
<h2>About page</h2>
</div>
);
}
all things are looking fine, but you should not leave className empty and inside BrowserRouter there should be only one wrapper so you should wrap all elements inside a div.
If you want to import {About, AboutTeam} from ..., then you need to export 2 variables:
export const About = ...
export const AboutTeam = ...
It's not advisable to have too many components in 1 file, but if you really want to import all, that is also possible:
import * as About from './About.js'
... <About.About /> ... <About.AboutTeam /> ...
use export instead of export default to export both the component from the same file (About.js)
//About.js
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import './css/Style.css';
const About=()=>{
return(
<div className="">
<h2>About page</h2>
</div>
);
}
const AboutTeam=()=>{
return(
<div className="">
<h2>About Team</h2>
</div>
);
}
export {About, AboutTeam};
and then import it in the file you need,
import {About, AboutTeam} from "./About.js";
Apart from the solution, one more thing to keep in mind is
component exported using export default, is imported like
import About from "./path of file";
component exported using export, is/are imported like
import {About, AboutTeam} from "./path of file";

Unexpected re-rendering of components

I'm trying to navigate back to a Menu component, but when I trigger a route to do so, the previous rendered Practice component is rendered in the root domain level, which should just be for the Menu component.
The solutions for similar questions on StackOverflow say to use exact in the route, but as you can see I have this in place.
How do I make this work as expected? Thanks.
Here's what I have...
App.js
import React from 'react';
import './App.css';
import PracticeContextProvider from './contexts/PracticeContext';
import {BrowserRouter as Router, Route, Switch, Link} from 'react-router-dom';
import Menu from './pages/Menu';
function App() {
return (
<div className="app">
<PracticeContextProvider>
<Menu />
</PracticeContextProvider>
</div>
);
}
export default App;
Menu.js
import React, { useContext } from 'react';
import {BrowserRouter as Router, Route, Switch, Link, useParams, useLocation, useRouteMatch} from 'react-router-dom';
import { PracticeContext } from '../contexts/PracticeContext';
import Practice from './Practice';
import ModuleLanguageSelector from '../components/ModuleLanguageSelector';
import ModuleListMenuItem from '../components/ModuleListMenuItem';
const Menu = () => {
const { modulesJson } = useContext(PracticeContext);
return (
<div>
<h1>Menu</h1>
<Router>
<Switch>
<Route exact path="/">
<ModuleLanguageSelector />
{ modulesJson && (
modulesJson.map(module => {
return (
<Link to={'/Practice/' + module._id} key={ module._id }>
<ModuleListMenuItem module={ module }></ModuleListMenuItem>
</Link>
)
})
)}
</Route>
<Route exact path="/Practice/:moduleId" component={Practice} />
</Switch>
</Router>
</div>
);
}
export default Menu;
Practice.js
import React, { useContext } from 'react';
import {BrowserRouter as Router, Route, Switch, Link, useParams, useLocation, useRouteMatch} from 'react-router-dom';
import { PracticeContext } from '../contexts/PracticeContext';
import Menu from './Menu';
import ModulePracticeAnswerArea from '../components/ModulePracticeAnswerArea';
import ModulePracticeQuestion from '../components/ModulePracticeQuestion';
import ModulePracticeProgress from '../components/ModulePracticeProgress';
import ModulePracticeTutorial from '../components/ModulePracticeTutorial';
const Practice = () => {
const { moduleId } = useParams();
const { questionIndex } = useContext(PracticeContext);
return (
<Router>
<div className="module-practice-screen">
<h1>Practice</h1>
<div className="module-practice-container">
<Link to={'/'}>
<button className="quit-practice">X</button>
</Link>
{
moduleId ?
<React.Fragment>
{/*<ModulePracticeTutorial moduleId={ moduleId } />*/}
<ModulePracticeProgress questionNumber={ questionIndex } />
<ModulePracticeQuestion moduleId={ moduleId } questionNumber={ questionIndex } />
<ModulePracticeAnswerArea moduleId={ moduleId } questionNumber={ questionIndex } />
</React.Fragment>
:
<h3>The menu should appear here!</h3>
}
</div>
</div>
<Switch>
<Route exact path="/" component={Menu} />
</Switch>
</Router>
);
};
export default Practice;
You don't need <Router> and <Switch> in Practice
const Practice = props => {
const { moduleId } = useParams();
const { questionIndex } = useContext(PracticeContext);
return (
<div>
<div className="module-practice-screen">
<h1>Practice</h1>
<div className="module-practice-container">
<Link to="/">
<button>X</button>
</Link>
{moduleId ? (
<React.Fragment>
{/*<ModulePracticeTutorial moduleId={ moduleId } />*/}
<ModulePracticeProgress questionNumber={questionIndex} />
<ModulePracticeQuestion
moduleId={moduleId}
questionNumber={questionIndex}
/>
<ModulePracticeAnswerArea
moduleId={moduleId}
questionNumber={questionIndex}
/>
</React.Fragment>
) : (
<h3>The menu should appear here!</h3>
)}
</div>
</div>
</div>
);
};
codesandbox

React.createElement: type should not be null, undefined.. When creating/rendering

So the full error is as follows...
I'm not sure why I'm receiving this error, I thought I created my component properly but maybe another eye can see what I'm doing wrong.
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import {
Step,
Stepper,
StepButton,
} from 'material-ui/Stepper';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
class AddProductStepper extends React.Component {
constructor(props) {
super(props);
this.state = {
stepIndex: 0
}
}
getStepContent(stepIndex) {
switch(stepIndex) {
case 0:
return 'Select campaign settings...';
case 1:
return 'What is an ad group anyways?';
case 2:
return 'This is the bit I really care about!';
default:
return 'You\'re a long way from home sonny jim!';
}
}
render() {
return(
<div style={{ width: '100%', maxWidth: 700, margin: 'auto' }}>
<Stepper
linear={false}
activeStep = {this.state.stepIndex}
>
<Step>
<StepButton onClick={() => this.setState({stepIndex: 0})}>
Select campaign settings
</StepButton>
</Step>
<Step>
<StepButton onClick={() => this.setState({stepIndex: 1})}>
Create an ad group
</StepButton>
</Step>
<Step>
<StepButton onClick = {() => this.setState({stepIndex:2})}>
Create an ad
</StepButton>
</Step>
</Stepper>
<div>
<p>{this.getStepContent(this.state.stepIndex)}</p>
<div style={{ marginTop: 12 }}>
<FlatButton
label="Back"
disabled={this.state.stepIndex === 0}
onClick={() => this.setState({stepIndex:this.state.stepIndex - 1})}
style={{ marginRight: 12 }}
/>
<RaisedButton
label="Next"
disabled={this.state.stepIndex === 2}
primary={true}
onClick{() => {
this.setState({stepIndex:this.state.stepIndex+ 1});
console.log(this.state);
}
}
/>
</div>
</div>
</div>
);
}
}
export default AddProductStepper;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
import React, { PropTypes } from 'react';
import ReactDOM from 'react-dom';
import {AddProductStepper} from './AddProductStepper';
class AddProduct extends React.Component {
constructor(props) {
super(props);
}
render() {
return <AddProductStepper />;
}
}
export default AddProduct;
I'm able to display the log, but it doesn't want to render the component. Am I incorrectly creating components? Thank you for your help in advance!
You're importing incorrectly. AddProductStepper is the default export of the module. You have to thus import it as a default export:
import AddProductStepper from './AddProductStepper';
The reason why you got the error was because you attempted to import the named export, which doesn't exist in the module. This yielded undefined, thus the error.

appbar responsive with options with react router v4, material-ui and apollo client

I'm working with apollo client, react, reac routerv4 and material-ui, my app is working ,
before insert material-ui i had
<Link to="/" className="navbar">React + GraphQL Tutorial</Link>
then i've inserted material-ui
<AppBar
title="Title"
iconClassNameRight="muidocs-icon-navigation-expand-more"
/>
but it's not clear for me how to add links for the title and options, in responsive mode with small screen the options i think must be invisible, in small screen not.
The official material-ui site is not well explained by example like bootstrap, so i need a litlle of help.
the full code is:
import React, { Component } from 'react';
import {
BrowserRouter,
Link,
Route,
Switch,
} from 'react-router-dom';
import './App.css';
import ChannelsListWithData from './components/ChannelsListWithData';
import NotFound from './components/NotFound';
import ChannelDetails from './components/ChannelDetails';
import AppBar from 'material-ui/AppBar';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {
ApolloClient,
ApolloProvider,
createNetworkInterface,
toIdValue,
} from 'react-apollo';
const networkInterface = createNetworkInterface({ uri: 'http://localhost:4000/graphql' });
networkInterface.use([{
applyMiddleware(req, next) {
setTimeout(next, 500);
},
}]);
function dataIdFromObject (result) {
if (result.__typename) {
if (result.id !== undefined) {
return `${result.__typename}:${result.id}`;
}
}
return null;
}
// customResolvers:
// This custom resolver tells Apollo Client to check its cache for a Channel object with ID $channelId
// whenever we make a channel query. If it finds a channel with that ID in the cache,
// it will not make a request to the server.
const client = new ApolloClient({
networkInterface,
customResolvers: {
Query: {
channel: (_, args) => {
return toIdValue(dataIdFromObject({ __typename: 'Channel', id: args['id'] }))
},
},
},
dataIdFromObject,
});
class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<BrowserRouter>
<MuiThemeProvider muiTheme={getMuiTheme()}>
<div className="App">
<Link to="/" className="navbar">React + GraphQL Tutorial</Link>
<AppBar
title="Title"
iconClassNameRight="muidocs-icon-navigation-expand-more"
/>
<Switch>
<Route exact path="/" component={ChannelsListWithData}/>
<Route path="/channel/:channelId" component={ChannelDetails}/>
<Route component={ NotFound }/>
</Switch>
</div>
</MuiThemeProvider>
</BrowserRouter>
</ApolloProvider>
);
}
}
export default App;
the right is add a code like this:
<AppBar position="static">
<Toolbar>
<IconButton color="contrast" aria-label="Menu">
</IconButton>
<Typography type="title" color="inherit" >
{"Admin"}
</Typography>
<AuthLink to="/customers" label="Customers"/>
<AuthLink to="/tours" label="Tours"/>
<AuthLink to="/signout" label="Sign Out"/>
<AuthLink to="/signin" label=" Sign In" whenLogged="false"/>
</Toolbar>
</AppBar>
Authlink is just a component that I wrote to show the options and where simple I add the Title to display options.
const AuthLink = (props) => {
let auth = checkAuth();
return (
( (auth && !props.whenLogged ) || (!auth && props.whenLogged == "false") ) ? (
<Link to={props.to} className="navbar"><Button>{props.label}</Button></Link>
) : (
null
)
);
}
"Button" is a component from material, "Link" from react-router, here the imports:
import {
BrowserRouter,
Link,
Route,
Switch,
Redirect,
} from 'react-router-dom';
import { MuiThemeProvider, createMuiTheme } from 'material-ui/styles';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import IconButton from 'material-ui/IconButton';