React not responsive - javascript

I'm a beginner in React. So I have 2 components - Login and Banner
**Login.js**
import React from 'react';
function login(){
return(
<div>
<b>Welcome back</b>
<p>Sign in to continue</p>
<div >
<input type = "text" placeholder="Email address" />
</div>
<div>
<input type="text" placeholder="Password"/>
</div>
<h6>Forgot your password?</h6>
<div>
<button>Log In</button>
</div>
<p>Don't have an account?<b> Sign Up instead</b></p>
</div>
)
}
export default login
**Banner.js**
import React from 'react';
import pic from './Banner.png';
function Banner(){
return(
<div >
<img src = {pic} />
</div>
)
}
export default Banner
So what I'm trying to do is display both the components when in desktop dimensions and display only the Login component when in mobile dimensions. I can't figure out how to go about it. When I go to mobile dimensions, the Login components moves on top of the banner as opposed to only showing Login.

Please check this example. Hope it helps you.
import React from 'react';
import PropTypes from 'prop-types';
import {makeStyles} from '#material-ui/core/styles';
import Hidden from '#material-ui/core/Hidden';
import withWidth from '#material-ui/core/withWidth';
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
},
container: {
display: 'flex',
flexWrap: 'wrap',
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
flex: '1 0 auto',
margin: theme.spacing(1),
},
}));
function ResponsiveExample(props) {
const classes = useStyles();
const {width} = props;
return (
<div className={classes.root}>
<Hidden mdDown>
<div className={classes.container}
style={{backgroundColor: '#499DF5', color: 'white', padding: '20px'}}>
<Banner/>
</div>
<div style={{backgroundColor: 'whitesmoke', color: 'green', padding: '20px'}}>
<Login/>
</div>
</Hidden>
<Hidden smUp>
<div style={{backgroundColor: 'whitesmoke', color: 'green', padding: '20px'}}>
<Login/>
</div>
</Hidden>
</div>
);
}
ResponsiveExample.propTypes = {
width: PropTypes.oneOf(['lg', 'md', 'sm', 'xl', 'xs']).isRequired,
};
export default withWidth()(ResponsiveExample);
function Banner() {
return (
<div>
<h1>This is Banner</h1>
</div>
)
}
function Login() {
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<form>
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" name='username'
className="form-control" id="username"/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="text" name='password' className="form-control" id="password"/>
</div>
<button type="submit" className="btn btn-primary">Login</button>
</form>
</div>
</div>
</div>
)
}

Related

React Google Maps Stuck on "Loading" when putting the StandaloneSearchBox in the code

I have a page on my react js where I am trying allow companies to register for my website and add their locations so that other companies come over for rentals, purchases, etc. I also need Markers if I can add them. I have gotten my Google Maps on my page, however, I can't get the Search bar (StandaloneSearchBox) on the page because it is stuck on "Loading". Here is my code:
import {useState, useEffect } from 'react'
import { GoogleMap, StandaloneSearchBox, LoadScript } from '#react-google-maps/api';
const initialState = {
company: '',
email: '',
password: '',
isMember: true,
}
const Register = () => {
const mapContainerStyle = {
height: "400px",
width: "800px"
}
const center = {
lat: -3.745,
lng: -38.523
};
const [values, setValues] = useState(initialState)
// global state and useNavigate
const handleChange = (e) => {
console.log(e.target)
}
const onSubmit = (e) => {
e.preventDefault()
console.log(e.target)
}
const handleLoad = ref => this.searchBox = ref;
const handlePlacesChanged = () => console.log(this.searchBox.getPlaces());
return (
<body class="page-template-default page page-id-13">
<header class="site-header">
<div class="container">
<h1 class="school-logo-text float-left"><strong>Direct</strong> Connection</h1>
<div class="site-header__util">
</div>
</div>
</header>
<div class="page-banner">
<div class="page-banner__bg-image" style={ { backgroundImage: "url('connection.jpg')" } }></div>
<div class="page-banner__content container container--narrow">
<h1 class="page-banner__title">Register</h1>
<div class="page-banner__intro">
<p></p>
</div>
</div>
</div>
<div class="container container--narrow page-section">
<h2 class="headline headline--tiny">Want to join and connect with companies? Sign up and get your company out there:</h2>
<label class="header">Profile Photo:</label>
<input id="image" type="file" name="profile_photo" placeholder="Photo" required="" capture></input>
<label class="company-name">Company Name</label>
<div class="company-input">
<input text="headline headline--input" placeholder="Enter Company"></input>
</div>
<label class="company-email">Email</label>
<div class="email-input">
<input text="headline headline--input" placeholder="Enter Email"></input>
</div>
<label class="company-map">Map</label>
<div class="map-input">
<LoadScript
googleMapsApiKey='API_HERE'>
<GoogleMap
id="map"
mapContainerStyle={mapContainerStyle}
center={center}
zoom={10}
>
<StandaloneSearchBox
onLoad={handleLoad}
onPlacesChanged={handlePlacesChanged}
>
<input
type="text"
placeholder="Customized your placeholder"
style={{
boxSizing: `border-box`,
border: `1px solid transparent`,
width: `240px`,
height: `32px`,
padding: `0 12px`,
borderRadius: `3px`,
boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
fontSize: `14px`,
outline: `none`,
textOverflow: `ellipses`,
position: "absolute",
left: "50%",
marginLeft: "-120px"
}}
/>
</StandaloneSearchBox>
</GoogleMap>
</LoadScript>
</div>
</div>
<footer class="site-footer">
<div class="site-footer__inner container container--narrow">
<div class="group">
<div class="site-footer__col-one">
<h1 class="school-logo-text school-logo-text--alt-color">
<strong>Direct</strong> Connection
</h1>
<p><a class="site-footer__link" href="index.html">706-263-0175</a></p>
</div>
</div>
</div>
</footer>
</body>
)
}
export default Register
I have tried adding more imports like from the ScriptLoaded file in the ../api/docs folder, however, it causes the whole page to go blank. If I get rid of the StandaloneSearchBox from import {} from '#react-google-maps/api' and from the LoadScript GoogleMap code, it has it on the page no problem, only it doesn't have the Search Bar and Markers to search for an address (StandaloneSearchBox)
I think the problem is that there was no library. In order for it to display the Search Box, there has to be a library. const lib = ['places']; is setting the places as a library and the library must be added to the LoadScript code where your API key goes. Updated code should have fixed the issue here:
import {useState, useEffect } from 'react'
import { GoogleMap, LoadScript, StandaloneSearchBox } from '#react-google-maps/api'
const lib = ['places'];
const mapContainerStyle = {
height: "400px",
width: "800px"
}
const center = {
lat: -3.745,
lng: -38.523
};
const position = {
lat: 37.772,
lng: -122.214
}
const initialState = {
company: '',
email: '',
password: '',
isMember: true,
}
const Register = () => {
const [searchBox, setSearchBox] = useState(null);
const handlePlacesChanged = () => console.log(searchBox.getPlaces());
const handleLoad = ref => {
setSearchBox(ref);
};
const [values, setValues] = useState(initialState)
// global state and useNavigate
const handleChange = (e) => {
console.log(e.target)
}
const onSubmit = (e) => {
e.preventDefault()
console.log(e.target)
}
return (
<body class="page-template-default page page-id-13">
<header class="site-header">
<div class="container">
<h1 class="school-logo-text float-left"><strong>Direct</strong> Connection</h1>
<div class="site-header__util">
</div>
</div>
</header>
<div class="page-banner">
<div class="page-banner__bg-image" style={ { backgroundImage: "url('connection.jpg')" } }></div>
<div class="page-banner__content container container--narrow">
<h1 class="page-banner__title">Register</h1>
<div class="page-banner__intro">
<p></p>
</div>
</div>
</div>
<div class="container container--narrow page-section">
<h2 class="headline headline--tiny">Want to join and connect with companies? Sign up and get your company out there:</h2>
<label class="header">Profile Photo:</label>
<input id="image" type="file" name="profile_photo" placeholder="Photo" required="" capture></input>
<label class="company-name">Company Name</label>
<div class="company-input">
<input text="headline headline--input" placeholder="Enter Company"></input>
</div>
<label class="company-email">Email</label>
<div class="email-input">
<input text="headline headline--input" placeholder="Enter Email"></input>
</div>
<label class="company-map">Map</label>
<LoadScript
googleMapsApiKey='API_HERE'
libraries={lib}
>
<GoogleMap
mapContainerStyle={mapContainerStyle}
center={center}
zoom={10}
>
<>
<StandaloneSearchBox
onLoad={handleLoad}
onPlacesChanged={handlePlacesChanged}
>
<input
type="text"
placeholder="Search"
style={{
boxSizing: `border-box`,
border: `1px solid transparent`,
width: `240px`,
height: `32px`,
padding: `0 12px`,
borderRadius: `3px`,
boxShadow: `0 2px 6px rgba(0, 0, 0, 0.3)`,
fontSize: `14px`,
outline: `none`,
textOverflow: `ellipses`,
position: "absolute",
left: "50%",
marginLeft: "-120px"
}}
/>
</StandaloneSearchBox>
</>
</GoogleMap>
</LoadScript>
</div>
<footer class="site-footer">
<div class="site-footer__inner container container--narrow">
<div class="group">
<div class="site-footer__col-one">
<h1 class="school-logo-text school-logo-text--alt-color">
<strong>Direct</strong> Connection
</h1>
<p><a class="site-footer__link" href="index.html">706-263-0175</a></p>
</div>
</div>
</div>
</footer>
</body>
)
}
export default Register

I want to render a background image for only this page not whole application but i am not able to do that i am still a new bee

this is my code for login page but i am not able to set bg image for this page i can do that by setting to app component which sets to whole application if i do the same to this then only the component is getting the background image not the whole page i am doing it by importing image
import React, { useState } from "react";
import "./Loginp.css";
import axios from "axios";
import bgimg from "../../assets/Loginimage.jpg";
function Loginp() {
const [usernamed, setusername] = useState("");
const [passwordd, setpassword] = useState("");
const check = false;
function clicki() {
console.log("clicked");
const dat = {
username: usernamed,
password: passwordd,
};
axios.post("http://localhost:7000/login", dat).then((resp) => {
check = resp.data;
});
if (check) {
alert("User name already exists");
}
}
return (
<div
id="loginform"
style={{
backgroundImage: bgimg,
height: 100,
marginTop: 10,
textAlign: "center",
}}
>
<FormHeader title="Login" />
{/* <Form /> */}
<div>
<div class="row">
<label>Username</label>
<input
type="text"
placeholder="Enter your username"
onChange={(e) => {
setusername(e.target.value);
}}
/>
</div>
<div class="row">
<label>Password</label>
<input
type="text"
placeholder="Enter your password"
onChange={(e) => {
setpassword(e.target.value);
}}
/>
</div>
<div id="button" class="row">
<button onClick={clicki}>Log in</button>
</div>
</div>
</div>
);
}
const FormHeader = (props) => <h2 id="headerTitle">{props.title}</h2>;
export default Loginp;
try this.
backgroundImage: url(${bgimg})

How to add a fixed button in the footer in material ui dialog?

I'm trying to create a dialog pop up for my react js app, when user clicks on button, dialog opens up. I have form with input fields in that dialog, after user fills out all inputs he can submit info by clicking "submit" button at the bottom of the dialog pop up. The problem is that I don't know how to stick submit button to the footer so even if there are 15+ inputs, user doesn't have to scroll all the way down to see "submit" button. I know that material ui has DialogActions for this purpose, but because dialog is in parent component, I don't have access to DialogActions from child. My code:
App.js (parent)
import React, { useState } from "react";
import Info from "./Info";
import Dialog from "#material-ui/core/Dialog";
import { DialogTitle } from "#material-ui/core";
import DialogContent from "#material-ui/core/DialogContent";
import DialogContentText from "#material-ui/core/DialogContentText";
import { DialogActions } from "#material-ui/core";
export default function App() {
const [open, setOpen] = useState(false);
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={handleClickOpen}>Click me to open dialog</button>
<Dialog
open={open}
aria-labelledby="responsive-dialog-title"
maxWidth="md"
setMaxWidth="md"
fullWidth={true}
>
<dialogContent>
<dialogTitle>
{" "}
<div>
<h4>Fill out the form</h4>
</div>
</dialogTitle>
<DialogContentText>
<Info />
</DialogContentText>
</dialogContent>
{/* <DialogActions>
<button id="responsive-dialog-title" onClick={handleClose}>
{" "}
Submit{" "}
</button>
</DialogActions> */}
</Dialog>{" "}
</div>
);
}
and Info.js (child) :
import React, { useState } from "react";
export default function Info() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const handleClickOpen = () => {
setOpen(true);
};
const handleSubmit = () => {
console.log(username);
console.log(password);
console.log(address);
};
return (
<form onSubmit={handleSubmit}>
<div
style={{
display: "flex",
flexDirection: "column",
width: "350px",
padding: "20px"
}}
>
<label> Username</label>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
type="text"
/>
</div>
<div
style={{
display: "flex",
flexDirection: "column",
width: "350px",
padding: "20px"
}}
>
<label> Password</label>
<input
value={password}
onChange={(e) => setPassword(e.target.value)}
type="password"
/>
</div>
<button> Submit</button>
</form>
);
}
codesandbox
Is there any way to make that "submit" button in Info.js displayed as DialogActions/ fixed to bottom? Any help and suggestion are greatly aprreciated.
Use the position: fixed property to achieve that. Your code would look like this:
<form onSubmit={handleSubmit}>
<div>
<div
style={{
display: "flex",
flexDirection: "column",
width: "350px",
padding: "20px"
}}
>
<label> Username</label>
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
type="text"
/>
</div>
<div
style={{
display: "flex",
flexDirection: "column",
width: "350px",
padding: "20px"
}}
>
<label> Password</label>
<input
value={password}
onChange={(e) => setPassword(e.target.value)}
type="password"
/>
</div>
</div>
<div style={{ position: "fixed" }}>
<button> Submit</button>
<button> Cancel</button>
</div>
</form>
The scroll that the dialog has by default also had to be removed
<Dialog
open={open}
aria-labelledby="responsive-dialog-title"
maxWidth="md"
setMaxWidth="md"
fullWidth={true}
>
<div style={{ overflow: "hidden", height: "100%", width: "100%" }}>
<dialogTitle>
{" "}
<div>
<h4>Fill out the form</h4>
</div>
</dialogTitle>
<Info />
</div>
</Dialog>
This works, but the best thing to do is call the submit function from the parent, or the submit function exists in the parent and the inputs can be filled with context or a simple state

Why is my React component state showing up in my url?

I have a login component in my cra app, and my state is showing up in my url, both in dev and production. I've replaced the email with {email}.
http://localhost:3000/?user={email}&password=password
I have no clue why this is happening. I have several other components, none of which exhibit the same behavior. I've also confirmed this is coming from the react component and not any of the route handling (I renamed the state and the url changed in kind).
How do I fix this?
import React from 'react';
import '../../App.css';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import LoginButton from './LoginButton';
class Card extends React.Component {
constructor(props) {
super(props);
this.handleInputChange = this.handleInputChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
state = {
user: "",
password: ""
};
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
onSubmit(){
this.props.login(this.state.user, this.state.password);
}
render(){
return (
<div style={styles.container}>
<form style={styles.form}>
<div style={styles.formContainer}>
<div style={styles.block}>
<div style={{display: 'flex', flexDirection: 'row'}}>
<i class="fas fa-user-circle" style={styles.iconPosition}></i>
<div style={{display: 'flex', flexDirection: 'column', flex: 5}}>
<div style={{display: 'flex', alignItems: 'start', marginBottom: '15px', fontFamily: 'Ubuntu', fontSize: '14pt'}}>
EMAIL
</div>
<input
type="text"
name="user"
value={this.state.user}
onChange={this.handleInputChange}
placeholder='john.snow#solidcad.ca'
style={{fontFamily: 'Ubuntu', fontSize: '10px', border: 'none'}}
/>
</div>
</div>
</div>
<div style={styles.block}>
<div style={{display: 'flex', flexDirection: 'row'}}>
<i class="fas fa-unlock-alt" style={styles.iconPosition}></i>
<div style={{display: 'flex', flexDirection: 'column', flex: 5}}>
<div style={{display: 'flex', alignItems: 'start', marginBottom: '15px', fontFamily: 'Ubuntu', fontSize: '14pt'}}>
PASSWORD
</div>
<input
type="password"
name="password"
value={this.state.password}
onChange={this.handleInputChange}
placeholder='*****'
style={{fontFamily: 'Ubuntu', fontSize: '10px', border: 'none'}}
/>
</div>
</div>
</div>
<LoginButton label='LOGIN' onClick={this.onSubmit}/>
</div>
</form>
</div>
);
}
}
export default connect(null, actions)(Card);
This is the app component that contains the login screen and the login:
import React, { Component } from 'react';
import { BrowserRouter, Route } from 'react-router-dom';
import { connect } from 'react-redux';
import './App.css';
import Configurator from './components/Configurator';
import LoginScreen from './components/Login/LoginScreen';
import * as actions from './actions';
const Dashboard = () => <h2>Dashboard</h2>
class App extends Component {
componentDidMount(){
this.props.fetchUser();
}
renderContent() {
switch (this.props.auth) {
case null:
return <LoginScreen />;
default:
return (
<BrowserRouter>
<Route exact path="/" component={Configurator}/>
{/* <Route path="/dashboard/" component={Dashboard}/> */}
</BrowserRouter>
)
}
}
render() {
return (
<div className="App" style={styles.container}>
{this.renderContent()}
</div>
);
};
}
function mapStateToProps({ auth, desAut }) {
return { auth, desAut };
}
export default connect(mapStateToProps, actions)(App);
Thanks in advance for the help!
preventDefault is what you're looking for, you can change the button type to submit in the LoginButton component like this <input type="submit" value="Login"/> and then
<form
style={styles.form}
onSubmit={(e) => {
e.preventDefault();
this.onSubmit();
}}
>
You have to provide an onSubmit handler on your form like this:
<form onSubmit={(event) => {
event.preventDefault();
...process form data...
}>
...
</form>

React infinite scroll keeps making requests forever

I am using this library https://www.npmjs.com/package/react-infinite-scroller for loading more when scroll reaches the end.
My code looks as below:
import React from 'react';
import {Route, Link} from 'react-router-dom';
import FourthView from '../fourthview/fourthview.component';
import {Bootstrap, Grid, Row, Col, Button, Image, Modal, Popover} from 'react-bootstrap';
import traineeship from './traineeship.api';
import Header from '../header/header.component';
import InfiniteScroll from 'react-infinite-scroller';
require('./traineeship.style.scss');
class Traineeship extends React.Component {
constructor(props) {
super(props);
this.state = {
companies: [],
page: 0,
resetResult: false,
};
}
componentDidMount() {
this.fetchCompanies(this.state.page);
}
fetchCompanies = page => {
traineeship.getAll(page).then(response => {
if (response.data) {
const companies = Array.from(this.state.companies);
this.setState({companies: companies.concat(response.data._embedded.companies)});
} else {
console.log(response);
}
});
};
render() {
return (
<div className={"wrapperDiv"}>
{JSON.stringify(this.props.rootState)}
<div className={"flexDivCol"}>
<div id="header">
<Header/>
</div>
<div id="result">
<div className={"search"}>
<h2>Harjoittelupaikkoja</h2>
<p className={"secondaryColor"}>{this.state.companies.length} paikkaa löydetty</p>
</div>
<div className={"filters"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
Hakukriteerit</h5>
<div className={"filter"}>Ravintola- ja cateringala</div>
<div className={"filter"}>Tarjoilija</div>
<div className={"filter"}>Kaikki</div>
</div>
<div className={"searchResults"}>
<h5 style={{marginTop: '30px', marginBottom: '10px'}} className={"primaryColor"}>
Hakutulokset</h5>
<InfiniteScroll
pageStart={0}
loadMore={ this.fetchCompanies }
hasMore={true || false}
loader={<div className="loader" key={0}>Loading ...</div>}
useWindow={false}
>
{
this.state.companies.map((traineeship, key) => (
<div id={"item"} key={key}>
<div className={"companyInfo"}>
<div className={"heading"}>
<div id={"companyDiv"}>
<p style={{
fontSize: '18px',
lineHeight: '18px'
}}>{traineeship.name}</p>
</div>
{
traineeship.video == null
? ''
:
<div id={"videoDiv"}>
<div className={"youtubeBox center"}>
<div id={"youtubeIcon"}>
<a className={"primaryColor"}
href={traineeship.mediaUrl}>
<span style={{marginRight: '3px'}}><Image
src="http://www.stickpng.com/assets/images/580b57fcd9996e24bc43c545.png"
style={{
width: '24px',
height: '17px'
}}/></span>
<span> <p style={{
fontSize: '13px',
lineHeight: '18px',
margin: 0,
display: 'inline-block'
}}>Esittely</p></span>
</a>
</div>
<div id={"txtVideo"}>
</div>
</div>
</div>
}
</div>
<div className={"location"}>
<div id={"locationIcon"}>
<Image src="assets/img/icLocation.png"
style={{marginTop: '-7px'}}/>
</div>
<div id={"address"}>
<a href={"https://www.google.com/maps/search/?api=1&query=" + encodeURI("Fredrikinkatu 4, Helsinki")}>
<p className={"primaryColor"}
style={{fontSize: '13px'}}>{traineeship.city}(show in
map)</p>
</a>
</div>
</div>
<div className={"companyDescription"}>
<p className={"secondaryColor"} style={{
fontSize: '14px',
lineHeight: '20px'
}}>{traineeship.description}</p>
</div>
<div className={"companyContacts"} style={{marginTop: '20px'}}>
<p className={"contactInfo"}>URL: {traineeship.website}</p>
<p className={"contactInfo"}>Email: {traineeship.email}</p>
<p className={"contactInfo"}>Puh: {traineeship.phonenumber}</p>
<p className={"contactInfo"}>Contact: {traineeship.contact}</p>
</div>
</div>
</div>
))
}
</InfiniteScroll>
</div>
</div>
</div>
</div>
);
}
}
export default Traineeship;
The problem is that it keep calling the fetchCompanies forever. Is there any fix for this?
In the documentation there is no samples of how the loadmore function should look like.
"hasMore" is always true in your case, make it false when there is no next URL.
problem, call function in render method
loadMore={ this.fetchCompanies }
Function call in componentDidMount and set state after use this.state print in template

Categories

Resources