Follow link when pressing enter - reactjs

I am using the react-router to pass input data from a search box when the user clicks the search button. However, when I press enter the input doesn't get passed over and the page just refreshes. Is there anyway I could set it so when the enter key is pressed the Nav routing happens?
import React, {useState} from 'react'
import '../sass/custom.scss';
import {Nav, Form, FormControl} from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
import {NavLink} from 'react-router-dom';
export const SearchBar = () => {
let [query, setQuery] = useState("")
return (
<div className="search-container">
<div className="row height d-flex justify-content-center align-items-center">
<div className="col-xs-12 col-sm-12 col-md-8 col-lg-8 my-5">
<div className="search"> <i className="fa fa-search"></i>
<Form className='d-flex mx-auto'>
<FormControl
type='search'
placeholder='Search'
className='form-control'
aria-label='Search'
onChange={e => setQuery(e.target.value) }
/>
<Nav.Link
as={NavLink}
exact={true}
to={{pathname:`/search`, state: `${query}` }}
className="search-button center btn btn-primary"
>
Search
</Nav.Link>
</Form>
</div>
</div>
</div>
</div>
)
}

Might not be the best solution, but you may give it a try
Just add onKeyPress on FormControl to track "enter key" and add preventDefault on form tag to prevent your page from reloading.
import React, { useState } from "react";
import '../sass/custom.scss';
import { Nav, Form, FormControl } from "react-bootstrap";
import 'bootstrap/dist/css/bootstrap.min.css';
import { NavLink, useHistory } from "react-router-dom";
export const SearchBar = () => {
let [query, setQuery] = useState("");
const history = useHistory();
return (
<div className="search-container">
<div className="row height d-flex justify-content-center align-items-center">
<div className="col-xs-12 col-sm-12 col-md-8 col-lg-8 my-5">
<div className="search">
<i className="fa fa-search"></i>
<Form
className="d-flex mx-auto"
onSubmit={(e) => e.preventDefault()}
>
<FormControl
type="search"
placeholder="Search"
className="form-control"
aria-label="Search"
onChange={(e) => setQuery(e.target.value)}
onKeyPress={(e: any) => {
if (e.nativeEvent.charCode === 13) {
history.push({ pathname: `/search`, state: `${query}` });
}
}}
/>
<Nav.Link
as={NavLink}
exact={true}
to={{ pathname: `/search`, state: `${query}` }}
className="search-button center btn btn-primary"
>
Search
</Nav.Link>
</Form>
</div>
</div>
</div>
</div>
);
};

Related

How to connect react js voice text to speech into search bar?

I want to add speech recognition for the search bar and I connect it with laravel controller. By typing anything I can search for products. I want to add a microphone and when tell something, search and display results. Accually I want to when tell something , it should display in search bar text. How I do this?
import React,{useState,useEffect} from 'react';
import {Link} from 'react-router-dom';
import axios from 'axios';
import swal from 'sweetalert';
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition';
function VoiceSearchBar() {
const [searchInput,setSearchInput] = useState({
searchtext:'',
});
const [searchResults,setSearchResults] = useState([]);
const handleInput = (e) =>{
e.persist();
setSearchInput({...searchInput,[e.target.name]:e.target.value})
}
const {
transcript,
listening,
resetTranscript,
browserSupportsSpeechRecognition
} = useSpeechRecognition();
if (!browserSupportsSpeechRecognition) {
return <span>Browser doesn't support speech recognition.</span>;
}
const submitSearch = (e) =>{
e.preventDefault();
const data = {
searchtext:searchInput.searchtext,
}
axios.post('api/store-search-text', data).then(res=>{
if(res.data.status === 200){
setSearchResults(res.data.text);
console.log(res.data.text);
}
else if(res.data.status === 404){
swal("Warning",res.data.message,"warning")
}
});
}
var results = "";
if(searchResults){
results = searchResults.map((item)=>{
return(
<div key={item.id} className="row">
<div className="col-sm-3">
<img src={`http://localhost:8000/${item.pimage}`} alt={item.name} width="50px"/>
</div>
<div className="col-sm-9">
<Link to={`/products/category/${item.category.slug}/${item.slug}`}><h6 data-bs-dismiss="modal">{item.name}</h6></Link>
<p>{item.meta_description}</p>
</div>
</div>
)
});
}
return (
<div>
<form onSubmit={submitSearch} className="d-flex">
<input className="form-control me-2" onChange={handleInput} value={searchInput.searchtext} type="search" name="searchtext" placeholder="Search" aria-label="Search" />
<div>
{/* <p>Microphone: {listening ? 'on' : 'off'}</p> */}
{/* <button onClick={SpeechRecognition.startListening}>start</button>
<button onClick={SpeechRecognition.stopListening}><button className="resetBtn" onClick={resetTranscript}></button>Stop</button>
<p>{transcript}</p> */}
</div>
<button className="btn btn-success" type="submit" data-bs-toggle="modal" data-bs-target="#staticBackdrop">Search</button>
</form>
<div class="modal fade" id="staticBackdrop" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="staticBackdropLabel">Search Results</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
{results}
</div>
</div>
</div>
</div>
</div>
);
}
export default VoiceSearchBar;

A component is changing controlled i/p to be uncontrolled. This is caused by value changing from defined to undefined Decide between using controlled/

this is my login.js
import React, { useState } from "react";
// import { BrowserRouter as Router, Route } from "react-router-dom";
import axios from "axios";
import { Redirect } from "react-router-dom";
import Footer from "./Bottom";
// import { FaUser, FaUnlock } from "react-icons/fa";
const Login = () => {
//functional component
const [login, setLogin] = useState({ username: "", password: "" });
// const [isSignUp, setisSignUp] = useState("");
let user;
const handleChange = (e) => {
const name = e.target.name;
const value = e.target.value;
setLogin({ ...Login, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault(); //reload the page
if (login.username && login.password) {
axios
.post("http://localhost:8080/api/registration/login", {
username: login.username,
password: login.password,
})
.then((response) => {
sessionStorage.setItem("user", JSON.stringify(response.data));
user = response.data;
console.log(user + "**********************");
var usertype = response.data.usertype;
console.log(usertype + "////////////");
console.log(user + "*********");
if (usertype === 1) return <Redirect to="/profile" />;
// window.location.href = "http://localhost:3000/profile";
// console.log("Seller");
else if (usertype === 0) return <Redirect to="/buyerprofile" />;
// window.location.href = "http://localhost:3000/buyerprofile";
// console.log("Buyer");
})
.catch((error) => {
console.log(error.response);
});
setLogin({ username: "", password: "" });
}
};
return (
<>
<head>
<link
rel="stylesheet"
href="font-awesome-4.7.0\css\font-awesome.min.css"
/>
</head>
<section className="vh-100">
<div className="container h-100">
<div className="row d-flex justify-content-center align-items-center h-100">
<div className="col-lg-8 col-xl-9">
<div className="card text-black" style={{ borderRadius: "25px" }}>
<div className="card-body p-md-5">
<div className="row justify-content-center">
<div className="col-md-10 col-lg-6 col-xl-7 order-2 order-lg-1">
<p className="text-center h1 fw-bold mb-5 mx-1 mx-md-4 mt-4">
Login
</p>
<form onSubmit={handleChange} className="mx-1 mx-md-4">
<div className="d-flex flex-row align-items-center mb-4">
<i
class="fa fa-user-circle fa-lg"
aria-hidden="true"
></i>
<div className="form-outline flex-fill mb-0">
<input
type="text"
id="username"
name="username"
className="form-control"
placeholder="User Name"
value={login.username}
onChange={handleChange}
/>
{/* {errors.username &&<p className="error">{errors.username}</p>} */}
</div>
</div>
<div className="d-flex flex-row align-items-center mb-4">
<i class="fa fa-unlock fa-lg" aria-hidden="true"></i>{" "}
<div className="form-outline flex-fill mb-0">
<input
type="password"
id="password"
name="password"
className="form-control"
placeholder="Password"
value={login.password}
onChange={handleChange}
/>
{/* {errors.password &&<p className="error">{errors.password}</p>} */}
</div>
</div>
<div className="d-flex justify-content-center mx-4 mb-3 mb-lg-4">
<button
type="submit"
className="btn btn-primary btn-lg"
onClick={handleSubmit}
>
Login
</button>
</div>
</form>
</div>
<div className="col-md-10 col-lg-6 col-xl-5 d-flex align-items-center order-1 order-lg-2">
<img/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<Footer />
</>
);
};
export default Login;
& if I try to login with my credentials it throws this error in console & this warning shows as soon as I start typing in input field
Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. at input
at div
at div
at form
at div
at div
at div
at div
at div
at div
at div
at section
at Login
I am new to react & I was trying my hands with react+sprinboot project, I saw some answers on uncontrolled input to controlled but here it's in-> reverse controlled input to uncontrolled,so what exactly is the difference?
Inside the handleChange function:
setLogin({ ...Login, [name]: value });
i think you meant to write "login" and not "Login", the warning may be caused by that.

"useHistory is not defined" in react js create-react-app

I am trying to build an easy password protected page with an hardcoded password and a random token generated, However I am getting multiple errors, the most prominent one being "userHistory" is not defined, there area host of other bugs but I intend to solve them as I am new to react, anybody here care to help? Please find below my code
import React, {useState} from 'react';
function Singmein () {
const [passwordInput, setPasswordInput] = useState('');
const history = useHistory();
function handlePasswordChange(e){
setPasswordInput(e.target.value);
}
const handleLoginSubmit = (e) => {
e.preventDefault();
let hardcodedCred = {
password: 'password123'
}
if ((passwordInput == hardcodedCred.password)) {
//combination is good. Log them in.
//this token can be anything. You can use random.org to generate a random string;
const token = '123456abcdef';
sessionStorage.setItem('auth-token', token);
//go to www.website.com/todo
history.push('/signin');
} else {
//bad combination
alert('wrong email or password combination');
}
}
}
class signin extends React.Component{
render () {
return (
<div className="d-flex flex-column flex-root">
<div className="login login-4 login-signin-on d-flex flex-row-fluid" id="kt_login">
<div className="d-flex flex-center flex-row-fluid bgi-size-cover bgi-position-top bgi-no-repeat" style={{backgroundColor: 'white'}}>
<div className="login-form p-7 position-relative overflow-hidden">
<div className="d-flex flex-center">
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</div>
<div className="card card-board" style={{backgroundColor: '#F0F1F4', width: '100%'}}>
<div className="card-body">
<div className="mb-10">
<h3 className="font-weight-bold">This website is password protected</h3>
</div>
<form className="form" autoComplete="off" id="kt_login_signin_form" onSubmit={handleLoginSubmit}>
<div className="form-group mb-5">
<label htmlFor="username">Enter Unique Password</label>
<input className="form-control h-auto form-control-solid py-4 px-8"
style={{backgroundColor: 'white'}}
type="password"
placeholder="Password"
name="password"
value={passwordInput}
onChange={handlePasswordChange} />
</div>
Enter
</form>
</div>
</div>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</div>
</div>
</div>
</div>
);
}
};
export default signin;
You need to import { useHistory } from 'react-router-dom';
You have to import react-router-dom like this:
import {useHistory} from "react-router-dom";
So, your full code will look like this:
import React, {useState} from 'react';
import {useHistory} from "react-router-dom";
function Singmein () {
const [passwordInput, setPasswordInput] = useState('');
const history = useHistory();
...
}

showing the applicants of a job in reactjs using id

Iam trying to make a react application whereby users are applying for a job and also creating a report that will show the profile of the users who have applied for the job. Iam welcome to any ideas that can be given to me since I would like to have a logic on how to implement that.
Here is my code below:
DriverCard.js
import React from "react";
import member2 from "../../../dist/images/user2.png";
const DriverCard = ({cardValues}) => {
return (
<>
<div className="col-lg-3 col-md-3 col-sm-4 col-6 p-0 mb-5">
<div className="text-center">
<div className="mb-2">
<img
src={cardValues ? `${cardValues.location.title}` : member2}
className="rounded-circle"
height="85px"
width="85px"
alt="members"
/>
</div>
<h6 className="mb-0 textHeading">
{cardValues ? cardValues.name : `John Doe`}
</h6>
<span className="text-muted textStyle"> #JohntheD 5h</span>
<hr
style={{
width: "50%",
marginTop: 4,
marginBottom: 1,
}}
/>
<h6 className="textStyle mt-1">
{cardValues ? `${cardValues.licenseAge} +years licence` : `NA`}
</h6>
<h6 className="textStyle">
{cardValues ? `${cardValues.experience} +years experience` : `NA`}
</h6>
</div>
</div>
</>
);
};
export default DriverCard;
This is the report file that is suppossed to show the jobcard and the profile for the applicants.
import React, { useEffect, useState } from "react";
import {useHistory} from "react-router-dom";
import map from "lodash/map"
import { getSpecificJobCard } from "../../Api/index";
import arrowBack from "../../dist/images/arrowBack.svg";
import DriverCard from "./Job_Components/DriverCard";
import JobCardDetails from "./Job_Components/JobCardDetails";
import NextPageButtons from "../Main/DashBoard_Buttons/NextPageButtons";
const JobDetails = ({jobpostId}) => {
const [jobCard, setjobCard] = useState([]);
const history = useHistory();
console.log("param val",jobpostId);
useEffect(() => {
(async () => {
let jobCardRespData = await getSpecificJobCard(jobpostId);
setjobCard(jobCardRespData);
console.log("jobcard response:", jobCardRespData);
})();
}, []);
console.log("resp list ----- ", jobCard);
return (
<div className="">
<div className="col-md-10 m-auto">
<span style={{ cursor: "pointer" }} className="">
<img src={arrowBack} alt="" className="img-fluid" />
</span>
<div className="row">
<div className="col-lg-4 mt-5">
<div className="row">
{}
<JobCardDetails job={jobCard} />
</div>
</div>
<div className="col-lg-8 mt-5">
<div className="row">
<DriverCard/>
{/* <DriverCard /> */}
</div>
</div>
</div>
<div className="row">
<div className="col-lg-12">
<div className="row">
</div>
</div>
</div>
</div>
<div className="col-lg-12 my-3 border-top">
<NextPageButtons/>
</div>
</div>
);
};
export default JobDetails;

Change auth state from custom component while using #aws-amplify with react

I am trying to integrate Amplify Auth with a React application.
I am using AmplifyAuthenticator from #aws-amplify/ui-react package to customize the auth flow.
Though I can use AmplifySignIn component and customize it, I want to create a totally custom instead of AmplifySignIn.
Following is what my custom component looks like:
import React from 'react';
import { Auth } from 'aws-amplify';
import { useForm } from "react-hook-form";
export default function CustomSignIn(props){
const { register, reset, errors, handleSubmit } = useForm();
const onSubmit = async data => {
await Auth.signIn(data.username, data.password);
};
return(
<form className="mt-5" onSubmit={handleSubmit(onSubmit)} slot={props.slot}>
<h4>Login</h4>
<p>Need an account? <span>Create an account</span></p>
<div className="form-group">
<label>Email address</label>
<input type="username" name="username" className="form-control" ref={register({required: true})}/>
</div>
<div className="form-group">
<label>Password</label>
<input type="password" name="password" className="form-control" ref={register({required: true})}/>
</div>
<button type="submit" class="btn btn-primary btn-block">Continue</button>
</form>
);
}
Following is how I am trying to manage auth state:
import React, {useEffect} from 'react';
import { AmplifyAuthenticator } from '#aws-amplify/ui-react';
import '../styles/App.scss';
import { AuthState, onAuthUIStateChange } from '#aws-amplify/ui-components';
import ProtectedRoutes from './ProtectedRoutes';
import logo from '../assets/logo.svg';
import CustomSignIn from '../modules/auth/CustomSignIn';
function App() {
const [authState, setAuthState] = React.useState();
const [user, setUser] = React.useState();
useEffect(() => {
return onAuthUIStateChange((nextAuthState, authData) => {
setAuthState(nextAuthState);
setUser(authData)
});
}, []);
return ( authState === AuthState.SignedIn && user )
?
(
<ProtectedRoutes />
)
:
(
<div className="container-fluid container-fluid--auth">
<div className="row">
<div className="col-md-8">
<div className="row">
<div className="col-12 py-3">
<img className="logo" src={logo} alt="logo" />
</div>
</div>
<div className="row">
<div className="col-md-4 offset-md-4">
<AmplifyAuthenticator>
<CustomSignIn slot="sign-in" />
</AmplifyAuthenticator>
</div>
</div>
</div>
<div className="col-md-4 col--auth-sidebar">
</div>
</div>
</div>
);
}
export default App;
The thing is, how do I take the user to the Sign Up page when the user clicks on the "Create an account" button on the Sign In page?

Resources