getting "Missing required parameter 'client_id'" error in react-google-login - reactjs

I inserted my client id correctly and it did work
but suddenly it's not working until now even though I didn't change any codes in <GoogleLogin />
Also it works in blank React when I tested but not working in this project
exact error message is Uncaught qw {message: "Missing required parameter 'client_id'", xM: true, stack: "gapi.auth2.ExternallyVisibleError: Missing require…YZKdHMHzzbYNF1G7KSEIjXaBQQw/cb=gapi.loaded_0:1:15"}
import React, { useState } from "react";
import "./CSS/Header.css";
import { BrowserRouter as Router, Link } from "react-router-dom";
import { GoogleLogin } from "react-google-login";
export default function Header() {
const responseGoogle = (response) => {
console.log(response);
};
return (
<Router>
<div id="header">
<div id="id"></div>
<h2 id="header_title">title</h2>
<div id="contents">
<h4 className="content">
<Link
to="/"
onClick={() => {
window.location.href = "/";
}}
>
HOME
</Link>
</h4>
<h4 className="content">
<Link
to="/history"
onClick={() => {
window.location.href = "/history";
}}
>
History
</Link>
</h4>
<GoogleLogin
clientid=[myclientid]
buttonText="Login"
onSuccess={responseGoogle}
isSignedIn={true}
onFailure={responseGoogle}
cookiePolicy={"single_host_origin"}
/>
</div>
</div>
</Router>
);
}

You should use clientId instead of clientid for the prop

Related

Keycloak 20.0.3 logout not working in react app (invalid redirect url)

I am trying to authenticate my react app using keycloak. The app is not able to successfully logout. I have setup the admin console to contain the post logout redirect url to be http://localhost:7171. The URL that shows on clicking logout button
http://localhost:8080/realms/hype/protocol/openid-connect/logout?client_id=hypeclient&post_logout_redirect_uri=http%3A%2F%2Flocalhost%3A7171%2F&id_token_hint=eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJZRHVhc0pTT0dIOUh2ZnRvZGNhRktmRkxuOEZuWmkzSVN3eVBQenlzazFVIn0.eyJleHAiOjE2NzU1NjU1ODUsImlhdCI6MTY3NTU2NTI4NSwiYXV0aF90aW1lIjoxNjc1NTY1MjcyLCJqdGkiOiI1MjEyODZlZS1hNThiLTRhMTUtYTgyZS1jODU2ZmE4NWVkZTEiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvcmVhbG1zL2h5cGUiLCJhdWQiOiJoeXBlY2xpZW50Iiwic3ViIjoiYzJhZTJiZWYtMjg2ZC00MDgzLTk3YTktMWEyM2YxNzQ4YzE0IiwidHlwIjoiSUQiLCJhenAiOiJoeXBlY2xpZW50Iiwibm9uY2UiOiI3NGUyMTk3Ni0zNzcwLTQzNWEtOTEzMC1lNGU2YWUyY2I4ZTIiLCJzZXNzaW9uX3N0YXRlIjoiYzAxZWJlYTEtMjAwYS00YzU3LTg2NTgtNjYyYTdjOTA5OThkIiwiYXRfaGFzaCI6IjNPczlxc0NucFdmYnFuRkNlZ1docmciLCJhY3IiOiIwIiwic2lkIjoiYzAxZWJlYTEtMjAwYS00YzU3LTg2NTgtNjYyYTdjOTA5OThkIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJuYW1lIjoia2FyYW4gc2hhaCIsInByZWZlcnJlZF91c2VybmFtZSI6ImthcmFuIiwiZ2l2ZW5fbmFtZSI6ImthcmFuIiwiZmFtaWx5X25hbWUiOiJzaGFoIn0.TFCh-dPE4h8HKpAapNv4socR7uAsKDnuVpqLiaZCguu1Vyztn_sUkrbaqFKJDeoIZv3XDzBDM5MezMvyRRkmiRIQTIbiTlYGgcNA5UkcwbeKioaowCWqYqyjG7A3D0lKNjf0MAF6PmWVrPJVbm8hYtQMVDHwWQ2vFTShnmMRJ2iTf4IeT1DDLANrLh3tMXeYMF2f9ZmvtNS72O-BICkD4uXPSyMiqnDgj_52UAdkEaLgkuv31TAYDAeVef-Rly8n7K5LG1MWytB2_-WrhwXwfxjymc9RH55Iy-1tvLUFceigO7XwQzffZYK5uJ9PXkbg3hlkr6QLVSXsiu8RYKQu9w
My Setup including the version looks like
Keycloak 20.0.3
Keycloak.js 20.0.3 via npm
react 18.2
App.JS
import React from "react";
import { ReactKeycloakProvider } from "#react-keycloak/web";
import keycloak from "./Keycloak";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import Nav from "./components/Nav";
import WelcomePage from "./pages/Homepage";
import SecuredPage from "./pages/Securedpage";
import PrivateRoute from "./helpers/PrivateRoute";
function App() {
return (
<div>
<ReactKeycloakProvider authClient={keycloak}>
<Nav />
<BrowserRouter>
<Routes>
<Route exact path="/" element={<WelcomePage />} />
<Route path="/secured"
element={<PrivateRoute>
<SecuredPage />
</PrivateRoute>}/>
</Routes>
</BrowserRouter>
</ReactKeycloakProvider>
</div>
);
}
export default App;
Nav.JS
import React from "react";
import { useKeycloak } from "#react-keycloak/web";
const Nav = () => {
const { keycloak, initialized } = useKeycloak();
function loginHelper(){
console.log("login clicked");
keycloak.login();
};
function logoutHelper(){
console.log("login clicked");
keycloak.logout();
};
return (
<div>
<div className="top-0 w-full flex flex-wrap">
<section className="x-auto">
<nav className="flex justify-between bg-gray-200 text-blue-800 w-screen">
<div className="px-5 xl:px-12 py-6 flex w-full items-center">
<h1 className="text-3xl font-bold font-heading">
Keycloak React AUTH.
</h1>
<ul className="hidden md:flex px-4 mx-auto font-semibold font-heading space-x-12">
<li>
<a className="hover:text-blue-800" href="/">
Home
</a>
</li>
<li>
<a className="hover:text-blue-800" href="/secured">
Secured Page
</a>
</li>
</ul>
<div className="hidden xl:flex items-center space-x-5">
<div className="hover:text-gray-200">
{!keycloak.authenticated && (
<button
type="button"
className="text-blue-800"
onClick={() => loginHelper()}
>
Login
</button>
)}
{!!keycloak.authenticated && (
<button
type="button"
className="text-blue-800"
onClick={() => logoutHelper()}
>
Logout ({keycloak.tokenParsed.preferred_username})
</button>
)}
</div>
</div>
</div>
</nav>
</section>
</div>
</div>
);
};
export default Nav;
Keycloak.JS
import Keycloak from "keycloak-js";
const keycloak = new Keycloak({
url: "http://localhost:8080",
realm: "hype",
clientId: "hypeclient",
});
export default keycloak;
PrivateRoute.JS
import { useKeycloak } from "#react-keycloak/web";
const PrivateRoute = ({ children }) => {
const { keycloak } = useKeycloak();
const isLoggedIn = keycloak.authenticated;
console.log("checking auth access " + isLoggedIn);
return isLoggedIn ? children : null;
};
export default PrivateRoute;
I have tried following this link but it does not work. Admin console looks like
Try changing
valid post logout urls to +
valid redirect urls to http://localhost:7171*

React : The path to the "404 not found" page if there is an error does not work

I am trying to redirect to an error page if a product ID is not found in a React project. I then find myself faced with a blank page and this error:
I created a Hook with UseEffect to retrieve data from an API
And here is the code for the page that should either return the products or the error page:
import React from "react";
import { useParams } from "react-router-dom";
import Rating from "../../Components/Rating";
import Slider from "../../Components/Slider";
import Tags from "../../Components/Tags";
import Host from "../../Components/Host";
import Error from "../Error";
import Accordion from "../../Components/Accordion";
import "./logement.css";
import { useFetch } from "../../utils/hooks";
function Logement() {
const { logementId } = useParams();
const {
data: logement,
isLoading,
error,
} = useFetch(`http://localhost:8000/logements/${logementId}`);
if (isLoading) return <h1>LOADING...</h1>;
if (error) {
return <Error />;
}
return (
<div className="logements__page">
<div className="logements__wrapper">
<Slider slides={logement.pictures} />
<div className="content">
<div className="informations">
<h1>{logement.title}</h1>
<p className="logement__location">{logement.location}</p>
<div className="tags__wrapper">
{logement.tags.map((tag, index) => (
<Tags key={index} getTag={tag} />
))}
</div>
</div>
<div className="rating__host">
<Rating rating={logement.rating} />
<Host host={logement.host} />
</div>
</div>
<div className="collapsible">
<Accordion title="Description" content={logement.description} />
<Accordion title="Equipement" content={logement.equipments} />
</div>
</div>
</div>
);
}
export default Logement;
Thank you for your answers
{(logement?.tags || []).map((tag, index) => (
Try it, and your problem will be solved!

i want to build sidebar on my own but the function don't work

Sorry for my bad English speak please help me to build a responsive sidebar menu. when i try to build a sidebar menu responsive I reach this type of error : TypeError: document.getElementByClassName is not a function. I haven't an idea where's the error exactly so this is my code of the sidebar menu:
import React from 'react';
import {useEffect} from 'react';
import SideNav, { Toggle, Nav, NavItem, NavIcon, NavText } from '#trendmicro/react-sidenav';
import '#trendmicro/react-sidenav/dist/react-sidenav.css';
import {listProducts} from '../actions/productActions';
import {useSelector, useDispatch} from 'react-redux';
function w3_open() {
document.getElementByClassName("sidebar").style.width = "100%";
document.getElementByClassName("sidebar").style.display = "block";
}
function w3_close() {
document.getElementByClassName("sidebar").style.display = "none";
}
export default function SideBarMenu() {
const dispatch = useDispatch();
useEffect(()=> {
dispatch(listProducts);
}, [])
const productList = useSelector((state) => state.productList);
const {products} = productList;
console.log(products);
return (
<div className="wrapper" >
<div className="section">
<div className="top_navbar">
<div className="hamburger">
<a href="#">
<i className="fa fa-bars" onClick={w3_open(), w3_close()} ><span className="bar-icon"> All products </span></i>
</a>
</div>
</div>
</div>
<div className="sidebar">
profile image & text
menu item
</div>
</div>
)
}
and this is the app.js file :
import React from 'react';
import {BrowserRouter, Routes, Route} from 'react-router-dom';
import HomePage from './Pages/HomePage';
import ProductPage from './Pages/productPage';
import SideBarMenu from './components/SideBarMenu';
function App() {
return (
<BrowserRouter>
<div className="grid-container" >
<header className="row" >
<div>
<a className="brand" href="/">My shop</a>
</div>
<div>
Cart
Sign In
</div>
</header>
<main>
<SideBarMenu ></SideBarMenu>
<Routes>
<Route path='/product/:id' element={<ProductPage /> } />
<Route path='/' element={<HomePage />} exact />
</Routes>
</main>
<footer className="row center" >All right reserved</footer>
</div>
</BrowserRouter>
);
}
export default App;
document.getElementByClassName(...) doesn't exist in JavaScript. You should use document.getElementsByClassName(...) (notice the plural in Elements).
Replace document.getElementByClassName("sidebar") with document.getElementsByClassName("sidebar")[0].
Update
To fix the error that you have right now, I would suggest to use a variable and useState Hook to display or hide the sidebar.
Example:
const [open, setOpen] = useState(false)
const handleSidebar = () => {
setOpen(!open)
}
return(
<div className = "wrapper" >
<div className = "section">
<div className = "top_navbar">
<div className = "hamburger">
<a href = "#">
<i className="fa fa-bars" onClick = {handleSidebar}><span className = "bar-icon"> All products </span></i>
</a>
</div>
</div>
</div>
{ open
? <div className = "sidebar">
profile image & text menu item
</div>
: null
}
</div>
)

How do I use the Use Navigate from React Router on a button that links to different pages?

I have a button that represents shop now that upon click it redirects you on different pages and the card elements have been mapped on external data.
I want this button to navigate to different pages kindly help.
const data =[
{
id:"Extensions",
Title:"Electrical Collections",
img:"/Assets/Electricals/Extlogo.png",
},
{
id:"Phone Accesorries",
Title:"Phone Accessories",
img:"/Assets/Phone/phoneacc.png",
},
{
id:"Homeware",
Title:"Homeware Collections",
img:"/Assets/Home/home.png",
},
]
function Home() {
let Navigate =useNavigate();
const handleElectricalPage = () =>{
Navigate("/extensionproduct")
}
<div className='cardContainer'>
{data.map((item )=>(
<card>
<div className='imageContainer'>
<img src={item.img} alt='Extension logo'/>
</div>
<div className='contentsContainer'>
<h2>{item.Title}</h2>
<div className='iconButtonContainer'>
<button onClick={handleElectricalPage}>Shop Now</button>
<ArrowForwardIcon className='arrowIcon'/>
</div>
</div>
Example from the react router https://reactrouter.com/docs/en/v6/api#usenavigate
navigate("../success", { replace: true });
You need to make an onClick handler (handleElectricalPage) dynamically, consider something like this.
function Home() {
let navigate =useNavigate();
return (
<div className='cardContainer'>
{data.map((item) => (
<card>
<button
onClick={() => navigate(`/externalProduct/${item.id}`)}
>
Shop Now
</button>
</card>
)}
</div>
}
You can also use Link which handles everything by itself
<Link to={`/externalProduct/${item.id}`}>
<button>Shop now</button>
</Link>
App.jsx
import { Routes, Route, Navigate } from "react-router-dom";
function App() {
return (
<div className="App">
<Routes>
<Route path="/" element={<Home />}>
<Route path="post/:id" element={<Detail />} />
</Route>
</Routes>
</div>
);
}
export default App;
Post.jsx
import React, { useState } from "react";
import {useNavigate} from 'react-router-dom'
export default function Post(props) {
const navigate = useNavigate()
{props.posts.map((post) => {
return (
<div className="post__container" key={post.id}>
<h4>
{post.id} {post.title}
</h4>
<p>{post.body}</p>
<button onClick={() => {return navigate(`${post.id}`)}}>Detail</button>
</div>
);
})}
}
Detail.jsx
import axios from 'axios'
import React, {useEffect, useState } from 'react'
import {useParams} from 'react-router'
export default function Detail (props) {
const params = useParams()
const [posts, setPosts] = useState({})
async function getById(id) {
const response = await axios.get("https://jsonplaceholder.typicode.com/posts/" + id)
setPosts(response.data)
}
useEffect(() => {
getById(params.id)
}, [params.id])
return (
<div>
<h2>Detail page: {params.id}</h2>
<h4>{posts.title}</h4>
<h5>{posts.body}</h5>
</div>
)
}

React: Props undefined when passed from Parent to Child Function Component

I have an Chat application.
In the App.js function component I have a messages state initialized as an empty array.
import React, { useState, useEffect } from 'react';
import './App.css';
import Sidebar from './Sidebar';
import Chat from './Chat';
import Pusher from 'pusher-js';
import axios from './axios';
function App() {
const [messages, setMessages] = useState([]);
useEffect(() => {
axios.get('http://localhost:9000/messages/sync')
.then(response => {
console.log(response.data);
setMessages(response.data);
})
}, [])
// when function component loads, run the follow once
useEffect(() => {
const pusher = new Pusher('1693ef51485e86ca1e9f', {
cluster: 'us2',
});
const channel = pusher.subscribe('messages');
channel.bind('inserted', (newMessage) => {
alert(JSON.stringify(newMessage));
setMessages([...messages, newMessage]);
});
return () => {
channel.unbind_all();
channel.unsubscribe();
};
}, [messages])
return (
<div className="app">
<div className="app_body">
<Sidebar />
<Chat messsages={messages}/>
</div>
</div>
);
}
export default App;
Once messages are stored there, the messages state is passed down as props to a function component in Chat.js.
import { Avatar, IconButton } from '#material-ui/core';
import SearchOutlinedIcon from '#material-ui/icons/SearchOutlined';
import AttachFileIcon from '#material-ui/icons/AttachFile';
import MoreVertIcon from "#material-ui/icons/MoreVert";
import InsertEmoticonIcon from '#material-ui/icons/InsertEmoticon';
import MicIcon from '#material-ui/icons/Mic';
import React from 'react';
import './Chat.css';
function Chat({ messages }) {
console.log(messages)
return (
<div className="chat">
<div className="chat_header">
<Avatar />
<div className="chat_headerInfo">
<h3>Room Name</h3>
<p>Last seen at...</p>
</div>
<div className="chat_headerRight">
<IconButton>
<SearchOutlinedIcon />
</IconButton>
<IconButton>
<AttachFileIcon />
</IconButton>
<IconButton>
<MoreVertIcon />
</IconButton>
</div>
</div>
<div className="chat_body">
{console.log(messages)}
{/**messages.map((message) => {
<p className={`chat_message ${message.received && "chat_receiver"}`}>
<span className="chat_name">{message.name}</span>
{message.message}
<span className="chat_timestamp">
{message.timestamp}
</span>
</p>
}) */}
</div>
<div className="chat_footer">
<InsertEmoticonIcon />
<form>
<input placeholder="Type a message"
type="text"
/>
<button type="submit">
Send a message
</button>
</form>
<MicIcon />
</div>
</div>
)
}
export default Chat
However messages is undefined in Chat.
Where is the error? I've experimented with passing props to chat as:
function Chat (props) {
{console.log(props.message)}
}
Nothing seems to work.
Check the spelling tripple sss - messsages in
return (
<div className="app">
<div className="app_body">
<Sidebar />
<Chat messsages={messages}/>
</div>
</div>
);
It's quite possible that your request to localhost in the first useEffect hook is not returning a value with the response. Double check your console output on that. As written, it should be working.
If that seems perfectly fine, then I would say that you need to clear your build cache.

Resources