How do I Import js file to React js file - javascript

JavaScript File.
const signUpButton = document.getElementById('signUp');
const signInButton = document.getElementById('signIn');
const container = document.getElementById('container');
signUpButton.addEventListener('click', () => {
container.classList.add("right-panel-active");
});
signInButton.addEventListener('click', () => {
container.classList.remove("right-panel-active");
});
I have this javascript Code, I want to use this in my React file.
This is my React js file Code.
import React, { Component } from 'react'
// import './js/main'
class Login extends Component {
render() {
return (
<div>
<div class="container" id="container">
<div class="form-container sign-up-container">
<form action="#">
<h1>Create Account</h1>
<div class="social-container">
<i class="fa fa-facebook-f" style={{color: 'blue'}} aria-hidden="true"></i>
<i class="fa fa-google-plus" style={{color: 'red'}} aria-hidden="true"></i>
<i class="fa fa-linkedin" style={{color: 'blue'}} aria-hidden="true"></i>
</div>
<span>or use your email for registration</span>
<input type="text" placeholder="Name" />
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
<button>Sign Up</button>
</form>
</div>
<div class="form-container sign-in-container">
<form action="#">
<h1>Sign in</h1>
<div class="social-container">
<i class="fa fa-facebook-f" style={{color: 'blue'}} aria-hidden="true"></i>
<i class="fa fa-google-plus" style={{color: 'red'}} aria-hidden="true"></i>
<i class="fa fa-linkedin" style={{color: 'blue'}} aria-hidden="true"></i>
</div>
<span>or use your account</span>
<input type="email" placeholder="Email" />
<input type="password" placeholder="Password" />
Forgot your password?
<button>Sign In</button>
</form>
</div>
<div class="overlay-container">
<div class="overlay">
<div class="overlay-panel overlay-left">
<h1>Welcome Back!</h1>
<p>To keep connected with us please login with your personal info</p>
<button class="ghost" id="signIn">Sign In</button>
</div>
<div class="overlay-panel overlay-right">
<h1>Hello, Friend!</h1>
<p>Enter your personal details and start journey with us</p>
<button class="ghost" id="signUp">Sign Up</button>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default Login
In this code there onclick events for scrolling the login form and get the signup page.
How do I use Javascript to perform click events. I am new to React. Help me to get out of this.

You should be doing the following
Create two separate components for signUpButton.js and signInButton.js, each. These components should include their respective event handlers as well
Import these two components into your main component (your main React.js file) and use them.
import { SignUpButton } from './signUpButton.js'
import { SignInButton } from './signUpButton.js'
Right now, in your JavaScript file, you are trying to directly access DOM elements using document.getElementById. This is not recommended in React
Its important that you go through the core react concepts here and understand these thoroughly. This will definitely help you in the long run
https://reactjs.org/docs/hello-world.html
Event Handling in React
https://reactjs.org/docs/glossary.html#events

class Login extends Component {
constructor(props) {
super(props);
this.state = {addClass: false}
}
toggle() {
this.setState({addClass: !this.state.addClass});
}
render() {
let Class = ['container'];
if(this.state.addClass) {
Class.push('right-panel-active');
}
return (
<div>
<div className={Class.join(' ')} id="container">
Putting this is did a great Job to me. Working as Expected.
<button className="ghost" id="signIn" onClick={this.toggle.bind(this)}>{this.state.addClass}Log In</button>
And Calling this on Button click. Solved this after doing tones of Research. Feeling very Happy as new Beginner React js Developer.

Related

Session values not updating without refresh

I am adding pseron name and username into session after successfull login. After login I redirect user to next component. I have shown person name in header which is common for all components. It is not showing person name in header after login. I have to refresh page and then it shows new value of session
Header Component Coding
import { useEffect, useState } from "react";
import { Link, NavLink, useNavigate } from "react-router-dom";
var Header=()=>
{
const [pname,setpname] = useState();
useEffect(()=>
{
if(sessionStorage.getItem("pname")!=null)
{
setpname(sessionStorage.getItem("pname"));
}
else
{
setpname("Guest");
}
},[pname])
return(
<div>
<div className="agileits_header">
<div className="container">
<div className="w3l_offers">
<p>Welcome {pname}</p>
</div>
<div className="agile-login">
<ul>
<li><Link to="/register"> Register </Link></li>
<li><Link to="/login">Login</Link></li>
</ul>
</div>
<div className="product_list_header">
<form action="#" method="post" className="last">
<input type="hidden" name="cmd" value="_cart"/>
<input type="hidden" name="display" value="1"/>
<button className="w3view-cart" type="submit" name="submit" value=""><i className="fa fa-cart-arrow-down" aria-hidden="true"></i></button>
</form>
</div>
<div className="clearfix"> </div>
</div>
</div>
<div className="logo_products">
<div className="container">
<div className="w3ls_logo_products_left1">
<ul className="phone_email">
<li><i className="fa fa-phone" aria-hidden="true"></i>Order online or call us : (+0123) 234 567</li>
</ul>
</div>
<div className="w3ls_logo_products_left">
<h1>super Market</h1>
</div>
<div className="w3l_search">
<form action="#" method="post">
<input type="search" name="Search" placeholder="Search for a Product..." required=""/>
<button type="submit" className="btn btn-default search" aria-label="Left Align">
<i className="fa fa-search" aria-hidden="true"> </i>
</button>
<div className="clearfix"></div>
</form>
</div>
<div className="clearfix"> </div>
</div>
</div>
<div className="navigation-agileits">
<div className="container">
<nav className="navbar navbar-default">
<div className="navbar-header nav_2">
<button type="button" className="navbar-toggle collapsed navbar-toggle1" data-toggle="collapse" data-target="#bs-megadropdown-tabs">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
</div>
<div className="collapse navbar-collapse" id="bs-megadropdown-tabs">
<ul className="nav navbar-nav">
<li className="active"><NavLink to="/home" className="act">Home</NavLink></li>
<li>Contact</li>
</ul>
</div>
</nav>
</div>
</div>
</div>
)
}
export default Header;
Login Page Coding
import { useState } from "react";
import { useNavigate } from "react-router-dom";
var Login=()=>
{
const [uname,setuname] = useState("");
const [pass,setpass] = useState("");
const [msg,setmsg] = useState("");
const mynavigate = useNavigate();
function onlogin()
{
fetch(`http://localhost:5000/api/login?username=${uname}&pass=${pass}`)
.then(resp=>resp.json())
.then(result=>
{
if(result.statuscode===1)
{
sessionStorage.setItem("pname",result.data.name)
sessionStorage.setItem("uname",result.data.username)
if(result.data.usertype=="admin")
{
mynavigate("/adminpanel");
}
else
{
mynavigate("/home");
}
}
else
{
setmsg("Wrong Username/Password");
}
}).catch((err)=>
{
console.log(err);
setmsg("Error Occured");
})
}
return(
<div>
<div className="breadcrumbs">
<div className="container">
<ol className="breadcrumb breadcrumb1 animated wow slideInLeft" data-wow-delay=".5s">
<li><span className="glyphicon glyphicon-home" aria-hidden="true"></span>Home</li>
<li className="active">Login Page</li>
</ol>
</div>
</div>
<div className="login">
<div className="container">
<h2>Login Form</h2>
<div className="login-form-grids animated wow slideInUp" data-wow-delay=".5s">
<input type="email" onChange={(e)=>setuname(e.target.value)} placeholder="Email Address" required=" " />
<input type="password" onChange={(e)=>setpass(e.target.value)} placeholder="Password" required=" " />
<input type="submit" value="Login" onClick={onlogin}/><br/>
{msg}
</div>
<h4>For New People</h4>
<p>Register Here (Or) go back to Home<span className="glyphicon glyphicon-menu-right" aria-hidden="true"></span></p>
</div>
</div>
</div>
)
}
export default Login;
App.js Coding
import './App.css';
import Header from './components/Header';
import Footer from './components/Footer';
import SiteRoutes from './components/SiteRoutes';
function App() {
return (
<div>
<Header/>
<SiteRoutes/>
<Footer/>
</div>
);
}
export default App;
I have tried various options and also tried to give refresh coding in header. But it gets into infinite loop. I also tried . But it is of no use. I think router command is not available in v6. I have also tried useEffect without dependency of pname, just with empty square brackets[]

Uncaught TypeError: Cannot read properties of undefined (reading 'params') react

I am creating an ecommerce with react. I'm trying to create a function who shows the product details. But I do not know how to approach this problem. After to be linked to the url of the details in the browser, the url is the right one, but the details are not renderer and get the following message:
ProductDetails.js:22 Uncaught TypeError: Cannot read properties of undefined (reading 'params')
Down here you can read the ProductDetails.js and App.js files.
This is my react-router-dom version v6.4.1
import { BrowserRouter, Route, Routes, Link } from 'react-router-dom';
import Header from './components/layout/Header';
import Footer from './components/layout/Footer';
import Home from './components/layout/Home'
import './App.css';
import ProductDetails from './components/product/ProductDetails';
function App() {
return(
<>
<Header/>
<Footer/>
<Routes>
<Route path='/' element={<Home/>} />
<Route path='/product/:id' element={<ProductDetails/>} />
<Route/>
</Routes>
</>
)
}
export default App;
import React, {useEffect, Fragment} from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getProductDetails, clearErrors } from '../../actions/productActions';
import { useAlert } from 'react-alert';
import Loader from '../layout/Loader';
import MetaData from '../layout/MetaData';
const ProductDetails = ({match}) => {
const dispatch = useDispatch();
const alert = useAlert();
const {loading, error, product} = useSelector(state => state.productDetails)
useEffect(()=>{
dispatch(getProductDetails(match.params.id))
if(error){
alert.error(error);
dispatch(clearErrors());
}
},[dispatch, alert, error, match.params.id])
return (
<Fragment>
{loading ? <Loader/> : (
<Fragment>
<div className="row f-flex justify-content-around">
<div className="col-12 col-lg-5 img-fluid" id="product_image">
<img src="https://i5.walmartimages.com/asr/1223a935-2a61-480a-95a1-21904ff8986c_1.17fa3d7870e3d9b1248da7b1144787f5.jpeg?odnWidth=undefined&odnHeight=undefined&odnBg=ffffff" alt="sdf" height="500" width="500"/>
</div>
<div className="col-12 col-lg-5 mt-5">
<h3>"{product.name}</h3>
<p id="product_id">Product # sklfjdk35fsdf5090</p>
<hr/>
<div className="rating-outer">
<div className="rating-inner"></div>
</div>
<span id="no_of_reviews">(5 Reviews)</span>
<hr/>
<p id="product_price">$108.00</p>
<div className="stockCounter d-inline">
<span className="btn btn-danger minus">-</span>
<input type="number" className="form-control count d-inline" value="1" readOnly />
<span className="btn btn-primary plus">+</span>
</div>
<button type="button" id="cart_btn" className="btn btn-primary d-inline ml-4">Add to Cart</button>
<hr/>
<p>Status: <span id="stock_status">In Stock</span></p>
<hr/>
<h4 className="mt-2">Description:</h4>
<p>Binge on movies and TV episodes, news, sports, music and more! We insisted on 720p High Definition for this 32" LED TV, bringing out more lifelike color, texture and detail. We also partnered with Roku to bring you the best possible content with thousands of channels to choose from, conveniently presented through your own custom home screen.</p>
<hr/>
<p id="product_seller mb-3">Sold by: <strong>Amazon</strong></p>
<button id="review_btn" type="button" className="btn btn-primary mt-4" data-toggle="modal" data-target="#ratingModal">
Submit Your Review
</button>
<div className="row mt-2 mb-5">
<div className="rating w-50">
<div className="modal fade" id="ratingModal" tabIndex="-1" role="dialog" aria-labelledby="ratingModalLabel" aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="ratingModalLabel">Submit Review</h5>
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
<ul className="stars" >
<li className="star"><i className="fa fa-star"></i></li>
<li className="star"><i className="fa fa-star"></i></li>
<li className="star"><i className="fa fa-star"></i></li>
<li className="star"><i className="fa fa-star"></i></li>
<li className="star"><i className="fa fa-star"></i></li>
</ul>
<textarea name="review" id="review" className="form-control mt-3">
</textarea>
<button className="btn my-3 float-right review-btn px-4 text-white" data-dismiss="modal" aria-label="Close">Submit</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</Fragment>
)}
</Fragment>
)
}
export default ProductDetails
1-) Add the following line of code at the beginning of your class:
import { useParams } from 'react-router-dom';
2-) Then add this function above your class (copy it exactly):
export function withRouter(Children){
return(props)=>{
const match = {params: useParams()};
return <Children {...props} match = {match}/>
}
}
3-) Next, change your class definition to this:
class EditExercises extends Component{
4-) Add the following line of code at the end of your class:
export default withRouter(EditExercises);

ReactStrap modal close icon is not getting show in the modal and How to use the header with some another tag

I am new to the react js. Here I am using the Modal of reactStrap.
<Modal isOpen={props.isOpen} centered='true'>
<ModalHeader>
Change this Question?
<button type="button" class="close" aria-label="Close" onClick={props.closeModal} ><span aria-hidden="true">×</span></button>
</ModalHeader>
<ModalBody>
<div className="row">
<div className="col-md-12 text-center ">
<Button type="submit" className="btn btn-outline-primary" onClick={props.showChangeQuestionModal} >Change by creating your own Question</Button>
</div>
</div>
<div className="row">
<div className="col-md-12 text-center marginForOrOption">
<span>or</span>
</div>
</div>
<div className="row">
<div className="col-md-12 text-center">
<Button type="submit" color="btn btn-primary">Change and Replace from Question bank</Button>
</div>
</div>
</ModalBody>
<ModalFooter>
</ModalFooter>
</Modal>
</div>
Now Here I have added that button to close modal . But In reactstrap it comes by default.But In my case it is not coming .
Another problem is that,
In the ModalHeader, It comes by default h5 so How can I change that ?
First question: You need to provide toggle method to your ModalHeader component's props if you want reactstrap to show its own close button so your ModalHeader should looks like:
<ModalHeader toggle={this.toggleModalMethod}>
Change this Question?
</ModalHeader>
Second question: You are not gonna do much with h5 inside of modal header but you definitely can change your h5 element style to make it looks how you want it to look:
<ModalHeader>
<span className="customStyleToOverrideDefault">Change this Question?</span>
</ModalHeader>
Please, dont forget to vote up for my answer if it helped you.

Refactoring jQuery for react component

I am moving away from using jQuery to do some quick hides, shows and css changes because I am using components in react that need to be re-rendered and thus are not triggering the jQuery actions that need a page refresh. I think my issue is that I need to set the state in each component but I am a bit confused as to how. Here is an example of the jquery for this particular view:
<script type="text/javascript">
$(document).ready(function () {
$(".schedule-times").hide();
$(".final-check").hide();
$(".available-time").on('click', function () {
$(".schedule-times").toggle();
});
$(".schedule-button").on('click', function () {
$('.finalize-timeline').css("background", "#4CAF50");
$(".final-check").show();
});
});
</script>
Here is an example of a component I have written:
import React, { Component } from 'react';
import '../../App.css';
import Calendar from '../Calendar';
import { Link } from 'react-router';
class Schedule_3 extends Component {
render() {
return (
<div className="wow fadeIn">
<div className="container">
<div className="timeline">
<div className="col-md-12 offset-md-2">
<div className="row">
<div className="col-md-2 timeline-box">
<div className="timeline-badge active-timeline">
<i className="fa fa-check wow bounceInDown"></i>
</div>
<span>How do you want to schedule?</span>
</div>
<div className="col-md-2 timeline-box">
<div className="timeline-badge active-timeline">
<i className="fa fa-check wow bounceInDown"></i>
</div>
<span>Pick your lesson type</span>
</div>
<div className="col-md-2 timeline-box">
<div className="timeline-badge active-timeline">
</div>
<span>Find a time</span>
</div>
<div className="col-md-2 timeline-box">
<div className="timeline-badge" id="no_border">
</div>
<span>Finalize</span>
</div>
</div>
</div>
</div>
<div className="row">
<div className="container">
<div className="col-md-6 offset-md-3">
<Calendar />
</div>
</div>
</div><br />
<div className="row schedule-times">
<div className="col-md-12 offset-md-2">
<div className="row">
<div className="col-md-4 offset-md-1">
<i className="fa fa-clock"></i>
10:30AM
</div>
<div className="col-md-2 offset-md-1">
<Link to="Schedule_4">
<button className="btn btn-primary">
Book Now
</button>
</Link>
</div>
</div><br />
<div className="row">
<div className="col-md-4 offset-md-1">
<i className="fa fa-clock"></i>
11:00AM
</div>
<div className="col-md-2 offset-md-1">
<button className="btn btn-primary">
Book Now
</button>
</div>
</div><br />
<div className="row">
<div className="col-md-4 offset-md-1">
<i className="fa fa-clock"></i>
11:30AM
</div>
<div className="col-md-2 offset-md-1">
<button className="btn btn-primary">
Book Now
</button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Schedule_3;
Looking at your code I would suggest the first thing you need to do is split it into smaller, more manageable and more readable components that are responsible for 1 thing.
As you have posted a big example I cannot show you how to do it for every case you have, but I can give you a simple example that can be adapted for your use cases.
class ToggleContent extends React.Component {
constructor() {
super();
this.state = { hidden: true };
this.toggleContent = this.toggleContent.bind(this);
}
toggleContent() {
this.setState(prevState => ({
hidden: !prevState.hidden
}));
}
render() {
const { hidden } = this.state;
const { children } = this.props;
return (
<div>
<button onClick={ this.toggleContent }>Toggle</button>
<div>
{ !hidden && children }
</div>
</div>
);
}
}
You can use this component like this <ToggleContent>Hello World</ToggleContent> and it will toggle visibility of Hello World on the button press. You can put anything inside of this, including other components, it doesn't have to just be text.
You can see an example of it running here.
You can see the state of whether the children are hidden or not is held in the component this.state = { hidden: true };.
The children are then rendered if it is not hidden, if !hidden === true. We can see that inline here { !hidden && children }.
The toggleContent method is then using the previous state to switch back and forth between hidden and showing.
toggleContent() {
this.setState(prevState => ({
hidden: !prevState.hidden
}));
}

Subscribe to Angular Material Mat-Drawer events .. Ex: openedChange

I'm using mat-drawer and I want to be notified in the associated Component, when the mat-drawer is opened and close to add some logic at that moment;
The html has the follosing structure :
<mat-drawer-container class="example-container" autosize>
<mat-drawer #drawer class="custom-sidenav" mode="side">
<div>
<button routerLink="/" routerLinkActive="active"
style="margin-top: 50px" mat-button class="small" (click)="showFiller = !showFiller" >
<mat-icon style="color: red">home</mat-icon>
<b style="margin-left: 20px">Home</b>
</button>
</div>
<div>
<button routerLink="/transactions" routerLinkActive="active" style="margin-top: 20px" mat-button class="small" (click)="showFiller = !showFiller" >
<mat-icon style="color:gray">trending_flat</mat-icon>
<b matBadge="{{totalTransactions}}" matBadgeColor="red" matBadgeOverlap="false" style="margin-left: 20px">Transactions</b>
</button>
</div>
<div *ngIf="isAdmin">
<button routerLink="/fetch-data" routerLinkActive="active" style="margin-top: 20px" mat-button class="small" (click)="showFiller = !showFiller" >
<mat-icon matBadge="{{totalCertificates}}" matBadgePosition="before" matBadgeColor="accent" style="color:gray">description</mat-icon>
<b style="margin-left: 20px">Certificates</b>
</button>
</div>
<div>
<button (click)="navigateToMyCertificates()" routerLinkActive="active" style="margin-top: 20px" mat-button class="small" (click)="showFiller = !showFiller" >
<mat-icon matBadge="{{myCertificates}}" matBadgePosition="before" matBadgeColor="accent" style="color:gray">description</mat-icon>
<b style="margin-left: 20px">My Certificates</b>
</button>
</div>
<div>
<button routerLink="/certificate-validator" routerLinkActive="active" style="margin-top: 20px" mat-button class="small" (click)="showFiller = !showFiller" >
<mat-icon style="color:black">check</mat-icon>
<b style="margin-left: 20px">Validate Certificate</b>
</button>
</div>
</mat-drawer>
and this is the associated Component class :
export class HomeLayoutComponent {
..etc
}
What is the required code that needs to be added in the mat-drawer and in the component to realize a correct binding that will fire the "openedChange" event in the Component class
Thanks !
There are 2 ways of doing it. You can either do
<mat-drawer #drawer (openedChange)="onOpenedChange($event)"></mat-drawer>
In your component you would then have a method
onOpenedChange(e: boolean)
Or you can do it using a view child in the component
export class MyComponent implements OnInit {
#ViewChild('drawer') drawer: MatDrawer;
ngOnInit() {
this.drawer.openedChange.subscribe((o: boolean) => { console.log(`IsOpen: ${o}`) });
}
}
you can go to the official website of angular material. They have a very nice doc of that.
Above answer is perfect.
Just adding some more info.
There are many other events like: openedStart, closedStart, onPositionChanged ... etc

Categories

Resources