ReactJs using CSS per page - node.js

I'm using ReactJs to build a simple app with 3 routes:
"/" <- index.js
"/login" <- login.js
"/register" <- register.js
to view these pages correctly, i need to import CSS-files.
But if i import the CSS-file for the "/login" route, it also gets loaded in the "/" route.
here are my files:
app.js
import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import './App.css';
import Index from './pages/index';
import Login from './pages/login';
import './css/bootstrap.css';
class App extends Component {
render() {
return (
<Router>
<Switch>
<Route exact path='/' component={Index} />
<Route exact path='/login' component={Login} />
</Switch>
</Router>
);
}
}
export default App;
index.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import logo from '../logo.svg';
import '../App.css';
class Index extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
<Link to={'/login'}>Login</Link>
</p>
</div>
);
}
}
export default Index;
and login.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import '../css/login.css';
import '../css/main.css';
import logo from '../img/s900x300.png';
import back from '../img/back.svg';
import view from '../img/view.svg';
export default class Login extends Component {
render() {
return (
<div>
<script async="" src="https://www.google-analytics.com/analytics.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button className="back">
<a><img alt="" className="left" src={back}/></a>
</button>
<div className="background">
</div>
<div id="login" className="container login">
<img alt="" src={logo} />
<center><h5>‌</h5></center>
<input name="user" type="text" required placeholder="Benutzername oder Email"/>
<div className="password">
<input name="pw" required maxLength="64" type="password" placeholder="Passwort"/>
<button id="view_toggle">
<img alt="" src={view}/>
</button></div>
<form>
<button id="login" className="on">Login</button>
</form>
<center><b><a>back</a> | <Link to={'/register'}><a>Create account</a></Link></b></center>
</div>
<script src="/js/bootstrap.min.js"></script>
</div>
);
}
}
for example: in my login.css want a background image for my body. but this background is also applied to "/". How can i prevent, that the css is used global? Sorry for my bad english :)

To avoid your issue, you can create a global css file like style.css
then you link it to your index.html
as #Chase DeAnda suggest you can establish namespace for each page.
your style.css should be something like
.login .myClass {...}
.login .anotherClass {...}
.main .myClass {...}
.main .anotherClass {...}

Related

I am having problems with setState

I'm working on a simple login site and to navigate between Login and Sign up site I made a state called "aktivSide" meaning "activeSite" which is supposed to determine whether the login site or the sign up site will display.
Whenever I click on the "Registrer Bruker" (sign up) button, I get this error message:
Uncaught TypeError: Cannot read properties of undefined (reading 'setState')
import planB from "./plan_b.json"
import logo from './bilder/logo.png'
import './App.css';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faEyeSlash, faEye } from '#fortawesome/free-solid-svg-icons'
import React from 'react';
class App extends React.Component {
//React
constructor(props) {
super(props);
this.state = {
aktivSide: "tom"
};
}
render() {
//JavaScript
return (
//jsx (javascript og HTML)
<>
<div onLoad={() => this.setState({ aktivSide: <LoggInn /> })} className="App">
<title>SpeedType</title>
<header className="App-header">
<div id="topp">
<img id="logoen" width={300} src={logo}></img>
</div>
<button onClick={() => console.log(this.state.aktivSide)}>state</button>
{this.state.aktivSide}
</header>
</div>
</>
)
function RegistrerBruker() {
return (
<>
<h1>Registrer Bruker</h1>
<input type="text" placeholder='brukernavn' className='input_text'></input>
<div className='passord'>
<input type="password" placeholder='passord' className='input_text'></input>
<FontAwesomeIcon className='eye_icon' id='eye_icon1' />
</div>
<p id='passordTekst'>tom</p>
<div className='knapper'>
<button className='knapper_login'><p>Logg Inn</p></button>
<button className='knapper_login'><p>Registrer deg</p></button>
</div>
</>
)
}
function LoggInn() {
//JavaScript
return (
//jsx
<>
<h1>Logg inn</h1>
<input type="text" placeholder='brukernavn' className='input_text'></input>
<div className='passord'>
<input type="password" placeholder='passord' className='input_text'></input>
<FontAwesomeIcon className='eye_icon' id='eye_icon1' />
</div>
<p id='passordTekst'>tom</p>
<div className='knapper'>
<button className='knapper_login'><p>Logg Inn</p></button>
<button onClick={() => this.setState({ aktivSide: <RegistrerBruker /> })} className='knapper_login'><p>Registrer deg</p></button>
</div>
</>
)
}
}
}
export default App;
I've tried adding:
this.aktivSide.bind(this);
to the constructor, but nothing will display.

React.js node not properly validating

So i gave made a login system, and it works fine, it's just that i try to only show my navbar after logging in, it worked at first, now it does not and i can't figure out why.
noder server.js
`
app.get("/login", (req, res)=> {
if (req.session.user) {
res.send({loggedIn: true, user: req.session.user})
}else{
res.send({loggedIn: false})
}
})
`
And here is the App.js where i try to see if they're logged in or not. If they are the menu should show, if not then it should not show.
`
import React, { useState } from "react";
import { Link } from "react-router-dom";
import Axios from "axios";
import Button from "./Button"
import { Cookie } from "express-session";
const Navbar = () => {
const Links = [
{name: "Home", link: "/home"},
{name: "Profile", link: "/profile"},
{name: "Settings", link: "/settings"},
];
const [openMenu, setOpenMenu] = useState(false)
return(
<div className="shadow-md w-full fixed top-0 left-0">
<div className="md:flex items-center justify-between bg-gray-800 dark:text-white py-4 md:px-10 px-7">
<div className="font-bold text-2xl cursor-pointer flex items-center">
Alex' file server
</div>
<div onClick={()=> {setOpenMenu(!openMenu)}} className="text-3xl absolute right-8 top-6 cursor-pointer md:hidden transition-transform duration-500">
<ion-icon name={openMenu ? "close" : "menu"}></ion-icon>
</div>
<ul className={`md:flex md:items-center md:pb-0 pb-12 absolute md:static bg-gray-800 md:z-auto z-[-1] left-0 w-full md:w-auto md:pl-0 pl-9 transition-all duration-500 ease-in ${openMenu ? "top-10 opacity-100" : "top-[-490px] md:opacity-100 opacity-0"}`}>
{
Links.map((link)=> (
<li key={link.name} className="md:ml-8 text-xl md:my-0 my-7">
<Link to={link.link} className="hover:text-teal-300 duration-500">{link.name}</Link>
</li>
))
}
<Button>
Logout
</Button>
</ul>
</div>
</div>
)
}
export default Navbar
`
I have tried to validate within the navbar itself, but that does not make sense

"Gets unauthorized error after submitting correct token"

I just try to hit the API when like and dislike button is clicked , but I get unauthorized error after passing the authorization header.
What is the solution of this problem. There is post where all users can like or dislike. There is only unauthorized error, everything is true.
This is the screenshot of where the action is written.
This is the screenshot where the error is displayed.
`JavaScript code
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'
import {Link} from 'react-router-dom';
import { deltePost, addLike, deleteLike } from
class PostItem extends Component {
onDelteClick(postId)
{
this.props.deltePost(postId);
}
onLikeClick(id)
{
this.props.addLike(id);
}
onunLikeClick(id)
{
this.props.deleteLike(id);
}
render() {
const {post,auth,showActions}=this.props;
return (
<section className="container">
<div className="posts">
<div className="post bg-white p-1 my-1">
<div>
<a href="profile.html">
<img
className="round-img"
src="//www.gravatar.com/avatar/05434e5d678bc30625550497804f6d0e?s=200&r=pg&d=mm"
alt=""
/>
<h4>{post.name}</h4>
</a>
</div>
<div>
<p className="my-1">
{post.text}
</p>
<p className="post-date">
{post.date}
</p>
{showActions ?(<span>
<button onClick={this.onLikeClick.bind(this, post._id)} type="button" className="btn btn-light">
<i className="fas fa-thumbs-up"></i>
<span>{post.likes.length}</span>
</button>
<button onClick={this.onunLikeClick.bind(this, post._id)} type="button" className="btn btn-light">
<i className="fas fa-thumbs-down"></i>
</button>
<Link to={`/post/${post._id}`} className="btn btn-primary">
Comments <span className='comment-count'>{post.comments.length}</span>
</Link>
{post.user === auth.user.id ?(
<button
type="button"
onClick={this.onDelteClick.bind(this,post._id)}
className="btn btn-danger"
>
<i className="fas fa-times"></i>
</button>
):null}
</span>) :null}
</div>
</div></div>
</section>
)
}
}
PostItem.defaultProps={
showActions:true
}
PostItem.propTypes={
deltePost:PropTypes.func.isRequired,
deleteLike:PropTypes.func.isRequired,
addLike:PropTypes.func.isRequired,
post:PropTypes.object.isRequired,
auth:PropTypes.object.isRequired
}
const mapStateToProps= state =>({
auth:state.auth
})
export default connect(mapStateToProps,{deltePost,addLike,deleteLike})(PostItem)
`

Why is my create react app giving no output?

I'm doing a tutorial for a basic CRUD app with React and Tailwind, this is my first time setting it up and I'm trying to display a navbar but when i run 'npm run start', the output is blank. Can anyone guide me as to why? Following this: https://www.unimedia.tech/2021/11/30/build-a-simple-crud-app-using-react-and-node/
App.js
import React from "react";
import { Link } from "react-router-dom";
export default function Navigate(){
return (
<nav class="flex items-center justify-between flex-wrap bg-green-500 p-6">
<div class="flex items-center flex-shrink-0 text-white mr-6">
<span class="font-semibold text-xl tracking-tight">REACT CRUD APP</span>
</div>
<Link to="/">
<button class="inline-block text-sm px-4 py-2 leading-none border rounded text-white border-white hover:border-transparent hover:text-green-500 hover:bg-white mt-4 lg:mt-0">
HOME
</button>
</Link>
</nav>
)
}
tailwind.config.js
module.exports = {
content: [
"./src/**/*.{js,jsx,ts,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
Navigate.js
import React from "react";
export default function Navigate(){
return (
<nav class="flex items-center justify-between flex-wrap bg-green-500 p-6">
<div class="flex items-center flex-shrink-0 text-white mr-6">
<span class="font-semibold text-xl tracking-tight">REACT CRUD APP</span>
</div>
<div>
<button class="inline-block text-sm px-4 py-2 leading-none border rounded text-white border-white hover:border-transparent hover:text-green-500 hover:bg-white mt-4 lg:mt-0">
CREATE
</button>
</div>
</nav>
)
}
index.css
#tailwind base;
#tailwind components;
#tailwind utilities;
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();
EDIT (New Output):
CHange your index.js file with this code. To work with Link you need to wrap your <App/> component with <BrowserRouter>. Also, it is best if you also add an output screenshot from the browser console as most of the time you will get detailed errors there.
import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();
So I have not worked with react recently so I don't know if something might be changed in the new react-router-dom version, but I am sure you need to wrap your App component into <Router></Router> tags to render the <Link> tag.
Make changes in App.js as below and it will display your navbar.
import React from "react";
import { Link, BrowserRouter as Router } from "react-router-dom";
export default function Navigate() {
return (
<Router>
<nav class="flex items-center justify-between flex-wrap bg-green-500 p-6">
<div class="flex items-center flex-shrink-0 text-white mr-6">
<span class="font-semibold text-xl tracking-tight">
REACT CRUD APP
</span>
</div>
<Link to="/">
<button class="inline-block text-sm px-4 py-2 leading-none border rounded text-white border-white hover:border-transparent hover:text-green-500 hover:bg-white mt-4 lg:mt-0">
HOME
</button>
</Link>
</nav>
</Router>
);
Let me know if this solution works out.

page does not redirect after setting token with localstorage

I am following the tutorial below to create a token system for my login application.
https://www.digitalocean.com/community/tutorials/how-to-add-login-authentication-to-react-applications
Here is my code:
App.js:
import logo from './logo.svg';
import './App.css';
import "bootstrap/dist/css/bootstrap.min.css";
import useToken from './components/useToken';
import Navbar from './components/Navbar';
import AudioDropzone from './components/AudioDropzone';
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useLocation
} from "react-router-dom";
import Upload from './pages/Upload';
import Manage from './pages/Manage';
import Menu from './pages/Menu';
import Admin from './pages/Admin';
import Login from './pages/Login';
import { useEffect, useState } from 'react';
<script src="https://unpkg.com/boxicons#latest/dist/boxicons.js"></script>
function App() {
const { token, setToken } = useToken();
console.log(token)
if(!token) {
return(
<div className="App">
<div className="row">
<div class="col-2">
</div>
<div class="col-9">
<Login setToken={setToken} />
</div>
</div>
</div>
);
}
return (
<div className="App">
<Router>
<head>
<link rel="stylesheet" href="boxicons.min.css" />
</head>
<div className="row" >
<div class="col-2">
</div>
<div class="col-9">
<Switch>
<Route path="/upload">
<Upload customer_id={token}/>
</Route>
<Route path="/manage">
<Manage customer_id={token} />
</Route>
<Route path="/menu">
<Menu customer_id={token} />
</Route>
<Route path="/admin">
<Admin />
</Route>
<Route path="/admin/upload">
<Upload />
</Route>
<Route path="/admin/manage">
<Manage />
</Route>
<Route path="/admin/menu">
<Menu />
</Route>
</Switch>
</div>
</div>
</Router>
</div>
);
}
export default App;
useToken.js:
import { useState } from 'react';
export default function useToken() {
const getToken = () => {
const tokenString = localStorage.getItem('token');
const userToken = JSON.parse(tokenString);
return userToken?.token
};
const [token, setToken] = useState(getToken());
const saveToken = userToken => {
localStorage.setItem('token', JSON.stringify(userToken));
setToken(userToken.token);
};
return {
setToken: saveToken,
token
}
}
Currently, when login is successful, it just clears the fields and shows the same login page again without showing the second version of App with all of my content. The issue is that the token value is not being updated and populated. I have verified that upon logging in token is updated to an integer value like 13.
This is seen when I log the value of userToken in useToken.js:
const saveToken = userToken => {
console.log(userToken) //returns 13
localStorage.setItem('token', JSON.stringify(userToken));
setToken(userToken.token);
};
Let me know what I am doing wrong!
I believe the bug is in the saveToken function.
setToken(userToken.token); should be setToken(userToken);
You don't need the .token because userToken is not an object. It is just an integer value.

Resources