Apply different background image for different pages in react js - css

I want to have a different background image for the login page and home page. If I apply the image to body tag then it gets applied to all the pages. And when I apply it to a specific login page, it works but it only gets applied according to the width and height of the login page.
Applied in body in index.css
body{
background-image: url("http://web3canvas.com/wp-content/uploads/2014/02/littlevisuals-high-quality-hd-banner-images-stock-photos-free-laptop-topview-download.jpg");
background-size: cover;
}
Here is the login page
And this is the home page
And I want background image in only login page.
When I apply background image to only login page, this happens.
I have applied that image in the outermost div of the login page.
<div className={classes.body}>
<React.Fragment>
<CssBaseline />
<main className={classes.layout}>
<Paper className={classes.paper}>
<Avatar className={classes.avatar}>
<LockIcon />
</Avatar>
<Typography variant="headline" className={classes.color}>Sign in</Typography>
<form onSubmit={this.handleSubmit}>
<FormControl margin="normal" required fullWidth>
<Field
component={renderTextField}
label="Email"
id="email"
name="email"
value={email}
onChange={this.handleChange}
fullWidth
/>
</FormControl>
<FormControl margin="normal" required fullWidth>
<Field
value={password}
onChange={this.handleChange}
name="password"
type="password"
id="password"
component={renderTextField}
label="Password"
className={classes.color}
fullWidth />
</FormControl>
<Button type="submit"
disabled={pristine || submitting}
fullWidth
variant="outlined"
color="secondary"
className={classes.submit}
>
Submit
</Button>
</form>
<Button
fullWidth
variant="outlined"
color="primary"
className={classes.submit}>
<Link to="/register">
New User ? Register Here
</Link>
</Button>
<SocialButton
fullWidth
variant="raised"
color="primary"
className="btn btn-danger form-control"
provider='google'
appId='967209745915-djav2bq5ic5r4ad9on3itp5a079s1ruu.apps.googleusercontent.com'
onLoginSuccess={this.handleSocialLogin}
onLoginFailure={this.handleSocialLoginFailure}
key={'google'}
>
Login with Google
</SocialButton>
</Paper>
</main>
</React.Fragment>
</div>
Help me out someone.
Edit --
I am using Material UI
This is the full login page code.
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { userActions } from '../../_actions';
import '../../index.css';
import axios from 'axios';
import { history } from '../../_helpers/history';
import SocialButton from '../../SocialButton';
import compose from 'recompose/compose';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Avatar from '#material-ui/core/Avatar';
import Button from '#material-ui/core/Button';
import CssBaseline from '#material-ui/core/CssBaseline';
import FormControl from '#material-ui/core/FormControl';
import Input from '#material-ui/core/Input';
import InputLabel from '#material-ui/core/InputLabel';
import LockIcon from '#material-ui/icons/LockOutlined';
import Paper from '#material-ui/core/Paper';
import Typography from '#material-ui/core/Typography';
import withStyles from '#material-ui/core/styles/withStyles';
import { Field, reduxForm } from 'redux-form'
import TextField from '#material-ui/core/TextField'
import { IndefiniteObservable } from '../../../node_modules/indefinite-observable';
const styles = theme => ({
layout: {
width: 'auto',
display: 'block', // Fix IE11 issue.
marginLeft: theme.spacing.unit * 3,
marginRight: theme.spacing.unit * 3,
[theme.breakpoints.up(400 + theme.spacing.unit * 3 * 2)]: {
width: 400,
marginLeft: 'auto',
marginRight: 'auto',
},
},
paper: {
marginTop: theme.spacing.unit * 13,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
padding: `${theme.spacing.unit * 2}px ${theme.spacing.unit * 5}px ${theme.spacing.unit * 5}px`,
background: 'linear-gradient(to bottom, rgba(146, 135, 187, 0.8) 0%, rgba(0,0,0,0.6) 100%)',
transition: 'opacity 0.1s, transform 0.3s cubic-bezier(0.17, -0.65, 0.665, 1.25)',
transform: 'scale(1)'
// backgroundImage: `url("http://web3canvas.com/wp-content/uploads/2014/02/littlevisuals-high-quality-hd-banner-images-stock-photos-free-laptop-topview-download.jpg")`,
},
body: {
backgroundImage: `url("http://web3canvas.com/wp-content/uploads/2014/02/littlevisuals-high-quality-hd-banner-images-stock-photos-free-laptop-topview-download.jpg")`,
backgroundSize: 'cover',
},
color: {
color: 'black',
},
avatar: {
margin: theme.spacing.unit,
backgroundColor: theme.palette.secondary.main,
},
form: {
width: '100%', // Fix IE11 issue.
marginTop: theme.spacing.unit,
},
submit: {
marginTop: theme.spacing.unit * 2,
marginBottom: theme.spacing.unit * 2
},
});
const renderTextField = ({
input,
label,
meta: { touched, error },
...custom
}) => (
<TextField
hintText={label}
floatingLabelText={label}
errorText={touched && error}
{...input}
{...custom}
/>
)
const validate = values => {
const errors = {}
const requiredFields = [
'firstName',
'lastName',
'email',
'favoriteColor',
'notes'
]
requiredFields.forEach(field => {
if (!values[field]) {
errors[field] = 'Required'
}
})
if (
values.email &&
!/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)
) {
errors.email = 'Invalid email address'
}
return errors
}
class LoginPage extends Component {
constructor(props) {
super(props);
// reset login status
this.props.dispatch(userActions.logout());
this.state = {
email: '',
password: '',
submitted: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleSocialLogin = this.handleSocialLogin.bind(this);
this.handleSocialLoginFailure = this.handleSocialLoginFailure.bind(this);
}
handleSocialLogin(user) {
console.log(user)
debugger;
if (user) {
this.props.dispatch(userActions.googlelogin(user));
}
}
handleSocialLoginFailure = (err) => {
console.error(err)
}
handleChange(e) {
const { name, value } = e.target;
this.setState({ [name]: value });
}
handleSubmit(e) {
debugger;
e.preventDefault();
this.setState({ submitted: true });
const { email, password } = this.state;
const { dispatch } = this.props;
if (email && password) {
dispatch(userActions.login(email, password));
}
}
render() {
const { classes } = this.props;
const { email, password, submitted } = this.state;
const { handleSubmit, pristine, reset, submitting } = this.props
return (
<div className={classes.body}>
<React.Fragment>
<CssBaseline />
<main className={classes.layout}>
<Paper className={classes.paper}>
<Avatar className={classes.avatar}>
<LockIcon />
</Avatar>
<Typography variant="headline" className={classes.color}>Sign in</Typography>
<form onSubmit={this.handleSubmit}>
<FormControl margin="normal" required fullWidth>
<Field
component={renderTextField}
label="Email"
id="email"
name="email"
value={email}
onChange={this.handleChange}
fullWidth
/>
</FormControl>
<FormControl margin="normal" required fullWidth>
<Field
value={password}
onChange={this.handleChange}
name="password"
type="password"
id="password"
component={renderTextField}
label="Password"
className={classes.color}
fullWidth />
</FormControl>
<Button type="submit"
disabled={pristine || submitting}
fullWidth
variant="outlined"
color="secondary"
className={classes.submit}
>
Submit
</Button>
</form>
<Button
fullWidth
variant="outlined"
color="primary"
className={classes.submit}>
<Link to="/register">
New User ? Register Here
</Link>
</Button>
<SocialButton
fullWidth
variant="raised"
color="primary"
className="btn btn-danger form-control"
provider='google'
appId='967209745915-djav2bq5ic5r4ad9on3itp5a079s1ruu.apps.googleusercontent.com'
onLoginSuccess={this.handleSocialLogin}
onLoginFailure={this.handleSocialLoginFailure}
key={'google'}
>
Login with Google
</SocialButton>
</Paper>
</main>
</React.Fragment>
</div>
);
}
}
LoginPage.propTypes = {
classes: PropTypes.object.isRequired,
};
function mapStateToProps(state) {
const { loggingIn } = state.authentication;
return {
loggingIn
};
}
export default compose(
withStyles(styles),
connect(mapStateToProps, null),
reduxForm({
form: 'MaterialUIForm',
validate
})
)(LoginPage);
I will put the code on stackblitz in a few minutes

Create unique classNames for each component, wrap other content inside the classNames div element.
for Login component
render() {
return (
<div className="login">
//other code
</div>
)
}
for Home component
render() {
return (
<div className="home">
//other code
</div>
)
}
In index.css apply the color for the classNames.
.login {
background: url("http://web3canvas.com/wp-content/uploads/2014/02/littlevisuals-high-quality-hd-banner-images-stock-photos-free-laptop-topview-download.jpg") no-repeat;
background-size: cover;
min-width: 100%;
min-height: 100%;
}
.home {
background: url("https://www.w3schools.com/cssref/mountain.jpg") no-repeat; background-size: cover;
min-width: 100%;
min-height: 100%;
}

If you want to use styled Components, which is fully compatible with Material UI,
you can just replace the <div className={classes.body}> with your custom <StyledBody>
import styled from 'styled-components';
const StyledBody = styled.div`
background: url('http://web3canvas.com/wp-content/uploads/2014/02/littlevisuals-high-quality-hd-banner-images-stock-photos-free-laptop-topview-download.jpg');
background-size: cover;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
`;
export default function Login(props) {
return (
<StyledBody>
// your login component
</StyledBody>
);
}
If you haven't already, be sure to install styled-components first with npm i styled-components
Of course the same css code would work however you want to use it.

document.body.style.backgroundImage = "url('image url')";

Related

Change the position of the buttons

I have a project, and in this project I have an interface that contains several fields in addition to two buttons, the first is “Create” and the second is “cancel”, and as it is clear in the picture the two buttons at the end, but I want the two buttons to be in the area in which there is writing in color red
How can I do that?
And the file for the interface is large, so I only put the method of writing the two buttons
main.js:
<div className="p-16 sm:p-24 max-w-2xl ">
<div className={tabValue !== 0 ? "hidden" : ""}>
<ShippingTab />
</div>
</div>
shipping.js:
import React, { useState } from "react";
import InputAdornment from "#material-ui/core/InputAdornment";
import TextField from "#material-ui/core/TextField";
import Grid from "#material-ui/core/Grid";
import "date-fns";
import DateFnsUtils from "#date-io/date-fns";
import {
KeyboardDatePicker,
MuiPickersUtilsProvider,
DatePicker,
} from "#material-ui/pickers";
import { makeStyles } from "#material-ui/core/styles";
import Button from "#material-ui/core/Button";
import CloudUploadIcon from "#material-ui/icons/CloudUpload";
import { addInvoice } from "../../../store/invoiceSlice";
import { motion } from "framer-motion";
import { useDispatch } from "react-redux";
import "react-datepicker/dist/react-datepicker.css";
import Slide from "#material-ui/core/Slide";
import { useSnackbar } from "notistack";
const useStyles = makeStyles((theme) => ({
root: {
"& > *": {
margin: theme.spacing(1),
},
},
input: {
display: "none",
},
button: {
margin: theme.spacing(1),
// padding: theme.spacing(4),
},
}));
function ShippingTab(props) {
const dispatch = useDispatch();
const classes = useStyles();
const [issueDate, setIssueDate] = useState(new Date());
const [dueDate, setDueDate] = useState(new Date());
const [netAmount, setNetAmount] = useState("");
const [taxNumber, setTaxNumber] = useState("");
const [grossAmount, setGrossAmount] = useState("");
const [file, setFile] = useState(null);
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const handleUploadPDFFileMessageClick = () => {
enqueueSnackbar(
"PDF file has been uploaded successfully",
{ variant: "success" },
{
anchorOrigin: {
vertical: "top",
horizontal: "right",
},
},
{ TransitionComponent: Slide }
);
};
const handleCreateInvoiceMessageClick = () => {
enqueueSnackbar(
"Invoice created successfully",
{ variant: "success" },
{
anchorOrigin: {
vertical: "top",
horizontal: "right",
},
},
{ TransitionComponent: Slide }
);
};
const fileSelectedHandler = (event) => {
console.log(event.target.files[0]);
const file = event.target.files[0];
if (event.target && file) {
// formData.append("invoice", file);
setFile(file);
}
};
const uploadHandler = (event) => {
const formData = new FormData();
formData.append("grossAmount", grossAmount);
formData.append("taxNumber", taxNumber);
formData.append("netAmount", netAmount);
formData.append("issueDate", issueDate);
formData.append("dueDate", dueDate);
formData.append("invoice", file);
console.log(
" invoice grossAmount,taxNumber,netAmount,",
file,
grossAmount,
taxNumber,
netAmount
);
console.log("dueDate,issueDate: ", dueDate, issueDate);
// call api
dispatch(addInvoice(formData));
};
const handleissueDateChange = (date) => {
setIssueDate(date);
console.log("date issssssssss: ", date);
console.log("date issssssssss: ", issueDate);
};
const handleDueDateChange = (date) => {
setDueDate(date);
};
const handleNetAmountChange = (event) => {
setNetAmount(event.target.value);
};
const handleTaxAmountChange = (event) => {
setTaxNumber(event.target.value);
};
const handleGrossAmountChange = (event) => {
setGrossAmount(event.target.value);
};
return (
<>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<div className="flex -mx-4">
<KeyboardDatePicker
inputVariant="outlined"
className="mt-8 mb-16"
margin="normal"
id="date-picker-dialog"
label="issue Date"
format="MM/dd/yyyy"
KeyboardButtonProps={{
"aria-label": "change date",
}}
value={issueDate}
onChange={handleissueDateChange}
/>
<KeyboardDatePicker
inputVariant="outlined"
className="mt-8 mb-16 ml-6"
margin="normal"
id="date-picker-dialog"
label="Due Date"
format="MM/dd/yyyy"
KeyboardButtonProps={{
"aria-label": "change date",
}}
value={dueDate}
onChange={handleDueDateChange}
/>
</div>
</MuiPickersUtilsProvider>
<TextField
className="mt-8 mb-16"
label="Net Amount"
id="extraShippingFee"
variant="outlined"
InputProps={{
startAdornment: <InputAdornment position="start">$</InputAdornment>,
}}
value={netAmount}
onChange={handleNetAmountChange}
fullWidth
/>
<TextField
className="mt-8 mb-16"
label="Tax Number"
id="extraShippingFee"
variant="outlined"
InputProps={{
startAdornment: <InputAdornment position="start">$</InputAdornment>,
}}
value={taxNumber}
onChange={handleTaxAmountChange}
fullWidth
/>
<TextField
className="mt-8 mb-16"
label="Gross Amount"
id="extraShippingFee"
variant="outlined"
InputProps={{
startAdornment: <InputAdornment position="start">$</InputAdornment>,
}}
value={grossAmount}
onChange={handleGrossAmountChange}
fullWidth
/>
<div className={classes.root}>
<input
accept="application/pdf"
className={classes.input}
id="contained-button-file"
// multiple
type="file"
onChange={fileSelectedHandler}
/>
<label htmlFor="contained-button-file">
<Button
variant="contained"
color="primary"
size="large"
component="span"
className={classes.button}
startIcon={<CloudUploadIcon />}
>
{/* <Button variant="contained" color="primary" component="span"> */}{" "}
Upload
</Button>
{/* </Button> */}
</label>
</div>
<motion.div
initial={{ opacity: 0, x: 20 }}
animate={{ opacity: 1, x: 0, transition: { delay: 0.3 } }}
>
<Grid
container
direction="row-reverse"
justifyContent="flex-start"
alignItems="flex-end"
>
<Grid item>
<Button
className="whitespace-nowrap mx-4"
variant="contained"
color="secondary"
// onClick={handleRemoveProduct}
>
Cancel
</Button>
</Grid>
<Grid item>
<Button
className="whitespace-nowrap mx-4"
variant="contained"
color="secondary"
// disabled={_.isEmpty(dirtyFields) || !isValid}
onClick={(ev) => {
uploadHandler();
ev.stopPropagation();
handleCreateInvoiceMessageClick(ev);
}}
>
Create
</Button>
</Grid>
</Grid>
</motion.div>
</>
);
}
export default ShippingTab;
You can align the two buttons to the left bottom using flex and height: 100%.
All the parents of the two buttons from the motion.div upwards including html and body need to have 100% height.
The grid that contains the buttons and motion.div need to have flex-grow:1 so that they occupy all the free space in their respective container.
html,
body {
height: 100%;
}
div.container {
height: 100%;
display: flex;
flex-direction: column;
}
section.red {
background: red;
padding: 5rem 0
}
section.blue {
background: blue;
padding: 5rem 0
}
section.green {
background: green;
flex-grow: 1;
display: flex;
}
section.green>div {
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
}
section.left {
flex-grow: 1;
display: flex;
justify-content: flex-end;
align-items: flex-end;
}
button {
padding: 1rem 2rem;
}
<div class="container">
<section class="red"></section>
<section class="blue"></section>
<section class="green">
<div>
<section class="right">
<button>Right</button>
</section>
<section class="left">
<button>One</button>
<button>TWO</button>
</section>
</div>
</section>
</div>
If ShippingTab has too many parents, it is hard to set 100% height on all of its parent. In that case, you may absolutely postion it either in the body or in its nearest relative container that has / can have 100% height.
The parent is a flex element, so try margin-top: auto; on the children (buttons or container thereof)

Element positioned absolute inside Dialog Material UI React

I have Dialog component where I have a button(bottom right corner) which shows another div with an item list. The problem I'm facing is that the list is being rendered inside the Dialog component and it's being cropped. I set the position: absolute, z-index and set the position: relative to the parent but it does not work. Here is how it looks like. Any helpful tips I would appreciate it.
1) Before I click the button to show the list
2) After I click the button. Highlighted css properties for the list element
And the code for Dialog component :
import React, { useState } from "react";
import { makeStyles } from "#material-ui/core";
import Button from "#material-ui/core/Button";
import Dialog from "#material-ui/core/Dialog";
import DialogContent from "#material-ui/core/DialogContent";
import DialogContentText from "#material-ui/core/DialogContentText";
import DialogTitle from "#material-ui/core/DialogTitle";
import IconButton from "#material-ui/core/IconButton";
import CloseIcon from "#material-ui/icons/Close";
import Typography from "#material-ui/core/Typography";
import OutlinedInput from "#material-ui/core/OutlinedInput";
import { ProjectTreeWindow } from "../index";
const useStyles = makeStyles(theme => ({
addTaskButton: {
marginTop: 10
},
dialog: {
width: "40%",
maxHeight: 435
},
closeButton: {
position: "absolute",
right: theme.spacing(1),
top: theme.spacing(1),
color: theme.palette.grey[500]
},
controlsWrapper: {
display: "flex",
alignItems: "center",
justifyContent: "space-between"
}
}));
const AddQuickTaskDialog = props => {
const classes = useStyles(props);
const { open, close } = props;
const [quickTaskDescription, setQuickTaskDescription] = useState("");
const [textInputRef, setTextInputRef] = useState(null);
const handleChangeQuickTaskDescription = event => {
setQuickTaskDescription(event.target.value);
};
const handleAddQuickTaskSubmit = () => {
alert("Quick task submitted");
close(textInputRef);
};
return (
<Dialog
data-testid="add-task-quick"
classes={{
paper: classes.dialog
}}
maxWidth="lg"
open={open}
keepMounted
onClose={() => {
close(textInputRef);
}}
aria-labelledby="quick-task-dialog"
aria-describedby="quick-task-dialog-description"
>
<DialogTitle id="quick-task-dialog-title">
<Typography variant="h6">Quick Add Task</Typography>
{close ? (
<IconButton
aria-label="close"
className={classes.closeButton}
onClick={() => {
close(textInputRef);
}}
>
<CloseIcon />
</IconButton>
) : null}
</DialogTitle>
<DialogContent>
<div className={classes.wrapper}>
<OutlinedInput
onChange={handleChangeQuickTaskDescription}
inputRef={input => {
setTextInputRef(input);
return input && input.focus();
}}
fullWidth
// className={showAddTaskInput ? classes.show : classes.hide}
placeholder="e.g. Take the dog out for a walk"
inputProps={{ "aria-label": "add task" }}
/>
<div className={classes.controlsWrapper}>
<Button
className={classes.addTaskButton}
disabled={quickTaskDescription.length === 0}
data-testId="quick-add-task-submit"
// onClick={handleAddTaskSubmit}
color="primary"
onClick={handleAddQuickTaskSubmit}
>
Add Task
</Button>
<ProjectTreeWindow />
</div>
</div>
</DialogContent>
</Dialog>
);
};
export default AddQuickTaskDialog;
and for the List component:
import React, { useState } from "react";
import { makeStyles } from "#material-ui/core";
import ListAltTwoToneIcon from "#material-ui/icons/ListAltTwoTone";
import IconButton from "#material-ui/core/IconButton";
import { CustomizedToolTip } from "../index";
import OutlinedInput from "#material-ui/core/OutlinedInput";
import DoneTwoToneIcon from "#material-ui/icons/DoneTwoTone";
import List from "#material-ui/core/List";
import ListItem from "#material-ui/core/ListItem";
import ListItemIcon from "#material-ui/core/ListItemIcon";
import ListItemText from "#material-ui/core/ListItemText";
import FiberManualRecordTwoToneIcon from "#material-ui/icons/FiberManualRecordTwoTone";
import { useProjectsValue, useSelectedProjectValue } from "../../context";
const useStyles = makeStyles(theme => ({
root: {
position: "absolute",
zIndex: 9999,
top: 200,
left: 0,
display: "flex",
flexDirection: "column",
"&:hover $child": {
visibility: "visible"
}
},
wrapper: {
position: "relative !important"
},
selected: {
"& $child": {
visibility: "visible !important"
}
},
hidden: {
visibility: "hidden"
},
listItemIcon: {
minWidth: 30
}
}));
const ProjectTreeWindowList = props => {
const [textInputRef, setTextInputRef] = useState(null);
const [typeProject, setTypedProject] = useState("");
const classes = useStyles(props);
const { projects } = useProjectsValue();
return (
<div className={classes.root}>
<OutlinedInput
// onChange={handleChangeQuickTaskDescription}
inputRef={input => {
setTextInputRef(input);
return input && input.focus();
}}
placeholder="Type a project"
inputProps={{ "aria-label": "select project" }}
/>
<List>
{projects &&
projects.map((project, index) => (
<ListItem
onClick={() => {
alert("move selected project to input");
}}
// selected={active === project.projectId}
button
// classes={{
// root: classes.root,
// selected: classes.selected
// }}
>
<ListItemIcon
className={classes.listItemIcon}
style={{ color: project.color }}
>
<FiberManualRecordTwoToneIcon />
</ListItemIcon>
<ListItemText primary={project.name} />
<ListItemIcon
className={`${classes.listItemIcon} ${classes.hidden}`}
>
<DoneTwoToneIcon />
</ListItemIcon>
</ListItem>
))}
</List>
</div>
);
};
const ProjectTreeWindow = props => {
const classes = useStyles(props);
const [showProjectTreeWindow, setShowProjectTreeWindow] = useState(false);
const handleShowProjectWindow = () => {
setShowProjectTreeWindow(!showProjectTreeWindow);
};
const handleCloseProjectWindow = () => {
setShowProjectTreeWindow(false);
};
return (
<div className={classes.wrapper}>
<CustomizedToolTip title="Select a project">
<IconButton onClick={handleShowProjectWindow} aria-label="add-project">
<ListAltTwoToneIcon />
</IconButton>
</CustomizedToolTip>
{showProjectTreeWindow ? <ProjectTreeWindowList /> : null}
</div>
);
};
export default ProjectTreeWindow;
It is because of the combinaison of position: relative and overflow-y: auto from the <Paper> component. If you override one of this property, it won't be hidden anymore.
To do this, there is a PaperProps property in <Dialog>.
Example:
<Dialog {...otherProps} PaperProps={{style: {position: 'static'} }}/>

Modal dialog to present description

I am trying to make a popup window with a description for the project whenever someone clicks the description button.
I can't figure out how to do it. I have looked for components in react-mdl but I don't know how to insert it to my program.
The hirarchy of the button is:
-App
---NAVBAR
---Pages
-------Projects
---------ProjectCard
------------description button
I have tried to integrate components from react-mdl, semantic-ui etc, but I couldn't figure out how to adapt it to my program.
Thanks in advance guys!
import React from "react";
import { Layout, Content } from "react-mdl";
import Pages from "./Pages";
import { NavBar } from "./NavBar";
import { LeftDrawer } from "./LeftDrawer";
class App extends React.Component {
render() {
return (
<div>
<Layout>
<NavBar />
<LeftDrawer />
<Content className="app-content">
<Pages />
</Content>
</Layout>
</div>
);
}
}
export default App;
import React from "react";
import { Tabs, Tab } from "react-mdl";
import { CProjects } from "./CProjects";
import { ReactProjects } from "./ReactProjects";
import { SwiftProjects } from "./SwiftProjects";
import { TypescriptProjects } from "./TypescriptProjects";
import { JavaProjects } from "./JavaProjects";
import { CPPProjects } from "./CPPProjects";
import { PythonProjects } from "./PythonProjects";
import { AssemblyProjects } from "./AssemblyProjects";
class Projects extends React.Component {
state = { activeTab: 0 };
handleChange = tabId => {
this.setState({ activeTab: tabId });
};
toggleCategiries = () => {
switch (this.state.activeTab) {
case 0:
return (
<div className="react-projects">
<ReactProjects />
</div>
);
case 1:
return (
<div className="typescript-projects">
<TypescriptProjects />
</div>
);
case 2:
return (
<div className="java-projects">
<JavaProjects />
</div>
);
case 3:
return (
<div className="c-projects">
<CProjects />
</div>
);
case 4:
return (
<div className="c++-projects">
<CPPProjects />
</div>
);
case 5:
return (
<div className="swift-projects">
<SwiftProjects />
</div>
);
case 6:
return (
<div className="python-projects">
<PythonProjects />
</div>
);
case 7:
return (
<div className="assembly-projects">
<AssemblyProjects />
</div>
);
default:
return <div>lala</div>;
}
};
render() {
return (
<div className="page">
<div className="categories">
<Tabs
activeTab={this.state.activeTab}
onChange={this.handleChange}
ripple
>
<Tab className="tab">React</Tab>
<Tab className="tab">TypeScript</Tab>
<Tab className="tab">Java</Tab>
<Tab className="tab">C</Tab>
<Tab className="tab">C++</Tab>
<Tab className="tab">Swift</Tab>
<Tab className="tab">Python</Tab>
<Tab className="tab">Assembly</Tab>
</Tabs>
{this.toggleCategiries()}
</div>
</div>
);
}
}
export default Projects;
import React from "react";
import {
Card,
CardTitle,
CardActions,
Button,
CardMenu,
IconButton,
CardText
} from "react-mdl";
import { Link } from "react-router-dom";
class ProjectCard extends React.Component {
render() {
const titleStyle = {
backgroundImage: "url(" + this.props.background + ")",
backgroundSize: "100% 100%",
color: "#fff",
height: "176px"
};
return (
<div>
<Card shadow={6} style={{ borderRadius: "6px" }}>
<CardTitle style={titleStyle}>{this.props.name}</CardTitle>
<CardText>{this.props.shortDescription}</CardText>
<CardActions border>
<div style={{ display: "flex", justifyContent: "center" }}>
<a href={this.props.github} target="_blank">
<Button colored>GitHub</Button>
</a>
<Button colored>Description</Button>
</div>
</CardActions>
<CardMenu style={{ color: "#fff" }}>
<IconButton name="share" />
</CardMenu>
</Card>
</div>
);
}
}
export default ProjectCard;
import React from "react";
import { Spring } from "react-spring/renderprops";
import ProjectCard from "./ProjectCard";
import backgroundImage from "../../additional-files/images/React_background.png";
export const ReactProjects = () => {
return (
<Spring
config={{ duration: 1000 }}
from={{ opacity: 0 }}
to={{ opacity: 1 }}
>
{props => (
<div style={props}>
<div className="projects">
<div className="project">
<ProjectCard
name="Lab1"
shortDescription="Encoder and Debug mode"
description="This is the desired description in Modal"
github="https://github.com/avishaiyaniv605/Computer-Architectue-Lab1"
background={backgroundImage}
/>
</div>
<div className="project">
<ProjectCard
name="Lab1"
shortDescription="Encoder and Debug mode"
description="This is the desired description in Modal"
github="https://github.com/avishaiyaniv605/Computer-Architectue-Lab1"
background={backgroundImage}
/>
</div>
<div className="project">
<ProjectCard
name="Lab1"
shortDescription="Encoder and Debug mode"
description="This is the desired description in Modal"
github="https://github.com/avishaiyaniv605/Computer-Architectue-Lab1"
background={backgroundImage}
/>
</div>
</div>
</div>
)}
</Spring>
);
};
I managed to do it with a Dialog component of evergreen ui.
Inserted it where the Description button was and inside it, I inserted the button
import React from "react";
import {
Card,
CardTitle,
CardActions,
Button,
CardMenu,
IconButton,
CardText
} from "react-mdl";
import Component from "#reach/component-component";
import { Pane, Dialog } from "evergreen-ui";
class ProjectCard extends React.Component {
state = {
active: false
};
handleToggle = () => {
this.setState({ active: !this.state.active });
};
actions = [
{ label: "Cancel", onClick: this.handleToggle },
{ label: "Save", onClick: this.handleToggle }
];
render() {
const titleStyle = {
backgroundImage: "url(" + this.props.background + ")",
backgroundSize: "100% 100%",
color: "#fff",
height: "176px"
};
return (
<div>
<Card shadow={6} style={{ borderRadius: "6px" }}>
<CardTitle style={titleStyle}>{this.props.name}</CardTitle>
<CardText>{this.props.shortDescription}</CardText>
<CardActions border>
<div style={{ display: "flex", justifyContent: "center" }}>
<a href={this.props.github} target="_blank">
<Button colored>GitHub</Button>
</a>
<Component initialState={{ isShown: false }}>
{({ state, setState }) => (
<Pane>
<Dialog
isShown={state.isShown}
title={this.props.name + " description"}
onCloseComplete={() => setState({ isShown: false })}
confirmLabel="close"
hasFooter={false}
>
<Pane height={1800} width="100%" backgroundColor="#ddd" style={{ borderRadius: '6px' }}>
<div style={{ padding: "1vw 0 0 1vw" }}>
{this.props.description}
</div>
</Pane>
</Dialog>
<Button colored onClick={() => setState({ isShown: true })}>
Description
</Button>
</Pane>
)}
</Component>
</div>
</CardActions>
<CardMenu style={{ color: "#fff" }}>
<IconButton name="share" />
</CardMenu>
</Card>
</div>
);
}
}
export default ProjectCard;

Extra Line coming inside Textfield component of material-ui with outlined borders

I am trying to use Textfield component of material ui package. I am using variant="outlined" property of it. But inside that Textfield line is also coming so looks bad from ui prespective.
Any idea how to show only ouline boundary.
(source: imggmi.com)
I guess Textfield by default puts that line. Its is the line just below Phone*.
import React, { Component } from "react";
import { connect } from "react-redux";
import { signIn } from "../../store/actions/authActions";
import { trySignUp } from "../../store/actions/authActions";
import { Redirect } from "react-router-dom";
import Container from "#material-ui/core/Container";
import CssBaseline from "#material-ui/core/CssBaseline";
import Avatar from "#material-ui/core/Avatar";
import Typography from "#material-ui/core/Typography";
import LockOutlinedIcon from "#material-ui/icons/LockOutlined";
import { withStyles } from "#material-ui/styles";
import FormControlLabel from "#material-ui/core/FormControlLabel";
import Checkbox from "#material-ui/core/Checkbox";
import TextField from "#material-ui/core/TextField";
import Button from "#material-ui/core/Button";
class SignIn extends Component {
render() {
const { authError, auth, classes } = this.props;
if (auth.uid) return <Redirect to="/" />;
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form onSubmit={this.handleSubmit} className={classes.form}>
{!this.state.isOTPSent && (
<TextField
variant="outlined"
margin="normal"
required
fullWidth
type="tel"
id="phone"
label="Phone"
name="phone"
autoComplete="phone"
autoFocus
onChange={this.handleChange}
/>
)}
{this.state.isOTPSent && (
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="otp"
label="OTP"
name="otp"
autoFocus
onChange={this.handleChange}
/>
)}
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/>
<div className="input-field">
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
id="loginButtonId"
onClick={this.state.isOTPSent ? this.handleSubmit : null}
className={classes.submit}
>
{this.state.isOTPSent ? "Login" : "Get OTP"}
</Button>
<div className="red-text center">
{authError ? <p>{authError}</p> : null}
</div>
</div>
</form>
</div>
</Container>
);
}
}
const styles = theme => ({
"#global": {
body: {
backgroundColor: "white"
}
},
paper: {
marginTop: 50,
display: "flex",
flexDirection: "column",
alignItems: "center"
},
avatar: {
margin: 1,
backgroundColor: "red"
},
form: {
width: "100%", // Fix IE 11 issue.
marginTop: 1
},
submit: {
margin: (3, 0, 2)
}
});
const mapStateToProps = state => {
return {
authError: state.auth.authError,
auth: state.firebase.auth
};
};
const mapDispatchToProps = dispatch => {
return {
signIn: phoneNumber => dispatch(signIn(phoneNumber)),
trySignUp: () => dispatch(trySignUp())
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(SignIn));
Need to remove the line.

React: How to include some standard size to box

I have been given some code which I do not fully understand. The project is hosted at: https://konekto.world/ and I am currently working on https://konekto.world/emergency_sent. I want the website to have a similar size in terms of size of textbox and padding as the one at https://konekto.world/. You can see the code below:
This is the screen I want to work on. As you can see I already wanted to apply style={padding} to the Grid but somehow this has no effect at all to the display.
import React from 'react';
import axios from 'axios';
//import Box from '#material-ui/core/Box';
import { makeStyles, withStyles } from '#material-ui/core/styles';
//import { styled } from '#material-ui/styles';
import { Header } from '../Layout';
import { CANCELLED } from 'dns';
import { Grid, Container, Box, Typography, Button } from '#material-ui/core';
//import { styled } from '#material-ui/styles';
import CONSTANTS from '../utils/Constants';
const styles = theme => ({
container: {
alignItems: 'center',
background: 'white',
border: 'black',
'border-width': 'medium',
'margin-top': '80px',
background: 'rgba(255, 255, 255, 0.8)',
'border-radius': '20px'
},
item: {
//background: 'red',
width: '80%',
//background: 'white',
'text-align': 'center',
'border-radius': '5px',
'margin-top': '10px'
},
label: {
background: 'white'
}
});
class EmergencySent extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.classes = props.classes;
}
render() {
var elementStyle = {
padding: 2,
textAlign: 'center',
fontSize: '12px'
};
var buttonStyle = {
padding: 10,
textAlign: 'center',
fontSize: '12px'
};
let location_display = null;
if (this.state.location) {
location_display = (
<Typography>
{this.state.location.longitude}, {this.state.location.latitude}
</Typography>
);
}
var padding = {
padding: '20px',
maxwidt: '200px'
};
/*
deleted after you location...
(logitude, latitude):
{location_display}
*/
return (
<React.Fragment>
<Header />
<Grid
container
className={this.classes.container}
direction="column"
spacing={2}
style={padding}
>
<Grid item sm={12} className={this.classes.item} />
<br />
<h2> Emergency sent!</h2>
<br />
<Typography>
Your location and personal information was transmitted. You will be contacted soon.
</Typography>
<br />
<Button
item
className={this.classes.item}
variant="contained"
color="primary"
onClick={this.onSpecify}
>
Specify Emergency
</Button>
<Typography>
<br />
Press the 'Specify Emergency'-button to enter details of your
emergency situation and guide incoming help.
</Typography>
<br />
<br />
<br />
<Button
className={this.classes.item}
item
variant="contained"
color="secondary"
onClick={this.onCancel}
>
Cancel Emergency
</Button>
<br />
</Grid>
</React.Fragment>
);
}
}
export default withStyles(styles)(EmergencySent);
The code for the first screen (https://konekto.world/ ) to which I want to have a similar screen is this:
import React from 'react';
import axios from 'axios';
import { Link as RouterLink } from 'react-router-dom';
import {
Grid,
Box,
IconButton,
Link,
Typography,
FormControl,
FormLabel
} from '#material-ui/core';
import ArrowForward from '#material-ui/icons/ArrowForward';
import { makeStyles, withStyles } from '#material-ui/core/styles';
import CONST from '../utils/Constants';
import CheckBoxGroup from './CheckBoxGroup';
import CheckBox from './CheckBox';
import SOSButton from './SOSButton';
const styles = theme => ({
container: {
alignItems: 'center',
// background: 'white',
border: 'black',
'border-width': 'medium',
'margin-top': '80px',
background: 'rgba(255, 255, 255, 0.8)',
'border-radius': '20px'
},
item: {
// background: 'red',
width: '100%',
//background: 'white',
'text-align': 'center',
'border-radius': '5px',
'margin-top': '10px'
},
label: {
// background: 'white'
}
// forwardbutton: {
// 'text-align': 'right'
// }
});
class FormEmergencyType extends React.Component {
//const classes = useStyles(); //React HOOK API => looks nice
constructor(props) {
super(props);
//const { classes } = props;
this.classes = props.classes;
this.state = {}
}
render() {
return (
<Grid
container
className={this.classes.container}
direction="column"
spacing={2}
>
<Grid item sm={12} className={this.classes.item}>
<Typography variant="h5">Who do you want to contact?</Typography>
<CheckBoxGroup>
<CheckBox
title="Ambulance"
onChange={this.handleChange}
checked={this.state['ambulance']}
value="ambulance"
/>
<CheckBox
title="Fire Service"
onChange={this.handleChange}
checked={this.state['fire_service']}
value="fire_service"
/>
<CheckBox
title="Police"
onChange={this.handleChange}
checked={this.state['police']}
value="police"
/>
<CheckBox
title="Car Service"
onChange={this.handleChange}
checked={this.state['car_service']}
value="car_service"
/>
<CheckBox
title="Emergency Contacts"
onChange={this.handleChange}
checked={this.state['emergency_contacts']}
value="emergency_contacts"
/>
</CheckBoxGroup>
<Grid />
<Grid
item
sm={12}
className={(this.classes.item, this.classes.forwardbutton)}
>
<SOSButton onSubmit={this.props.onSubmit} />
</Grid>
</Grid>
</Grid>
);
}
}
export default withStyles(styles)(FormEmergencyType);
Thank you very much for your help!
When using material ui, to modify styles you need to put them inside the styles object. Then inside the component you make the component's class name classes.something. So what if you notice the Grid component has a className of classes.container so all you need to do is to add the padding styles to container inside the style object like so
import React from "react";
import axios from "axios";
//import Box from '#material-ui/core/Box';
import { makeStyles, withStyles } from "#material-ui/core/styles";
//import { styled } from '#material-ui/styles';
import { Header } from "../Layout";
import { CANCELLED } from "dns";
import { Grid, Container, Box, Typography, Button } from "#material-ui/core";
//import { styled } from '#material-ui/styles';
import CONSTANTS from "../utils/Constants";
const styles = theme => ({
container: {
alignItems: "center",
background: "white",
border: "black",
"border-width": "medium",
"margin-top": "80px",
background: "rgba(255, 255, 255, 0.8)",
"border-radius": "20px",
padding: "20px",
maxWidth: "200px"
},
item: {
//background: 'red',
width: "80%",
//background: 'white',
"text-align": "center",
"border-radius": "5px",
"margin-top": "10px"
},
label: {
background: "white"
}
});
class EmergencySent extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { classes } = this.props;
var elementStyle = {
padding: 2,
textAlign: "center",
fontSize: "12px"
};
var buttonStyle = {
padding: 10,
textAlign: "center",
fontSize: "12px"
};
let location_display = null;
if (this.state.location) {
location_display = (
<Typography>
{this.state.location.longitude}, {this.state.location.latitude}
</Typography>
);
}
var padding = {};
/*
deleted after you location...
(logitude, latitude):
{location_display}
*/
return (
<React.Fragment>
<Header />
<Grid
container
className={classes.container}
direction="column"
spacing={2}
>
<Grid item sm={12} className={classes.item} />
<br />
<h2> Emergency sent!</h2>
<br />
<Typography>
Your location and personal information was transmitted. You will be
contacted soon.
</Typography>
<br />
<Button
item
className={classes.item}
variant="contained"
color="primary"
onClick={this.onSpecify}
>
Specify Emergency
</Button>
<Typography>
<br />
Press the 'Specify Emergency'-button to enter details of your
emergency situation and guide incoming help.
</Typography>
<br />
<br />
<br />
<Button
className={classes.item}
item
variant="contained"
color="secondary"
onClick={this.onCancel}
>
Cancel Emergency
</Button>
<br />
</Grid>
</React.Fragment>
);
}
}
export default withStyles(styles)(EmergencySent);

Resources