Can't find variable setUserEmail - node.js

I'm linking my backend with my frontend in react native and I get this error Can't find-variable: setUserEmail when I go to type in an email into the TextInput. I'm working on the login page and use a fetch API to log the user into the app. I followed a tutorial to the point but I'm getting this error each time I try to enter an email, I get a message say setUserEmail is declared but never used. Any help would be greately appreciated
import React, { Component, useState, createRef } from 'react';
import { StyleSheet, Text, TextInput, View, Dimensions, StatusBar, TouchableOpacity,Keyboard } from 'react-native';
export default function Login(){
const [userEmail, setUserEmail] = useState('');
const [userPassword, setUserPassword] = useState('');
const [loading, setLoading] = useState(false);
const handleSubmitPress = () => {
setLoading(true);
let dataToSend = {userEmail: userEmail, password: userPassword};
let formBody = [];
for (let key in dataToSend) {
let encodedKey = encodeURIComponent(key);
let encodedValue = encodeURIComponent(dataToSend[key]);
formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');
fetch('http://localhost:3000/users/users', {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Cache-Control": "no-cache",
Pragma: "no-cache",
Expires: "0",
},
body: JSON.stringify({
userEmail: userEmail,
password: userPassword,
os: Platform.OS === "ios" ? "iOS" : "Android",
}),
})
.then((response) => response.json())
.then((responseJson) => {
//Hide Loader
setLoading(false);
console.log(responseJson);
// If server response message same as Data Matched
if (responseJson.status === 'success') {
AsyncStorage.setItem('user_id', responseJson.data.email);
console.log(responseJson.data.email);
navigation.replace('DrawerNavigationRoutes');
} else {
setErrortext(responseJson.msg);
console.log('Please check your email id or password');
}
})
.catch((error) => {
//Hide Loader
setLoading(false);
console.error(error);
});
}
return(
<View style={style.container}>
<View style={style.parent}>
<Text style={style.title}>Login</Text>
<Text style={style.heading}>Please Sign in to continue</Text>
</View>
<View style={style.root}>
<TextInput name='txtEmail' placeholder='someone#something.com' style={style.email} onChangeText={(UserEmail) => setUserEmail(UserEmail)}/>
<TextInput type='password' name='txtPassword' placeholder='Password' secureTextEntry={true} style={style.password} onChangeText={(UserPassword) => setUserPassword(UserPassword)}/>
<Text style={style.forgotpassword}>Forgot Password?</Text>
<TouchableOpacity
title="Login"
style={style.login}
onPress={handleSubmitPress()}>
<Text style={style.login_caption}>Login </Text>
</TouchableOpacity>
</View>
<StatusBar hidden />
</View>
);
}
const style = StyleSheet.create({
container:{
width: Dimensions.get('window').width,
height: Dimensions.get('window').height,
},
forgotpassword:{
textAlign: 'right',
marginTop: 10,
},
login:{
width: 150,
height: 45,
backgroundColor: '#FFB900',
position: 'absolute',
right: 0,
marginLeft: 25,
marginRight: 15,
marginTop: 150,
borderRadius: 25,
},
login_caption:{
color: '#fff',
textAlign: 'left',
paddingLeft: 15,
justifyContent: 'center',
paddingTop: 12,
},
parent:{
marginTop: 85,
},
title:{
fontSize: 36,
fontWeight: "900",
paddingLeft: 25,
},
heading:{
color: '#C0C0C0',
paddingLeft: 25,
},
root:{
width: 250,
height: 350,
marginTop: 85,
alignSelf: 'center',
},
email:{
width: 275,
height:38,
borderColor: "#111",
borderWidth: 1,
fontSize: 16,
paddingLeft:10,
justifyContent: 'center',
borderRadius: 15,
alignSelf: 'center',
},
password:{
width: 275,
height:38,
borderColor: "#111",
alignSelf: 'center',
borderWidth: 1,
fontSize: 16,
paddingLeft:10,
justifyContent: 'center',
marginTop: 15,
borderRadius: 15,
}
});
UPDATED WITH CHANGES

With a little bit of cleaning, that what I ended up with:
import AsyncStorage from "#react-native-community/async-storage";
import React, { useState } from "react";
import { Dimensions, Platform, StatusBar, StyleSheet, Text, TextInput, TouchableOpacity, View } from "react-native";
const Login = () => {
const [userEmail, setUserEmail] = useState("");
const [userPassword, setUserPassword] = useState("");
const [errorText, setErrorText] = useState("");
const [loading, setLoading] = useState(false);
const handleSubmitPress = () => {
setLoading(true);
const dataToSend = { userEmail: userEmail, password: userPassword };
let formBody = [];
for (const key in dataToSend) {
const encodedKey = encodeURIComponent(key);
const encodedValue = encodeURIComponent(dataToSend[key]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
fetch("http://localhost:3000/users/users", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Cache-Control": "no-cache",
Pragma: "no-cache",
Expires: "0",
},
body: JSON.stringify({
userEmail: userEmail,
password: userPassword,
os: Platform.OS === "ios" ? "iOS" : "Android",
}),
})
.then((response) => response.json())
.then((responseJson) => {
//Hide Loader
setLoading(false);
console.log(responseJson);
// If server response message same as Data Matched
if (responseJson.status === "success") {
AsyncStorage.setItem("user_id", responseJson.data.email);
console.log(responseJson.data.email);
// navigation.replace('DrawerNavigationRoutes');
} else {
setErrorText(responseJson.msg);
console.log("Please check your email id or password");
}
})
.catch((error) => {
//Hide Loader
setLoading(false);
console.error(error);
});
};
return (
<View style={styles.container}>
<View style={styles.parent}>
<Text style={styles.title}>Login</Text>
<Text style={styles.heading}>Please Sign in to continue</Text>
</View>
<View style={styles.root}>
<TextInput
name="txtEmail"
placeholder="someone#something.com"
style={styles.email}
onChangeText={(UserEmail) => setUserEmail(UserEmail)}
/>
<TextInput
type="password"
name="txtPassword"
placeholder="Password"
secureTextEntry={true}
style={styles.password}
onChangeText={(UserPassword) => setUserPassword(UserPassword)}
/>
<Text style={styles.forgotpassword}>Forgot Password?</Text>
<TouchableOpacity title="Login" style={styles.login} onPress={handleSubmitPress}>
<Text style={styles.login_caption}>Login </Text>
</TouchableOpacity>
</View>
<StatusBar hidden />
</View>
);
};
const styles = StyleSheet.create({
container: {
height: Dimensions.get("window").height,
width: Dimensions.get("window").width,
},
email: {
alignSelf: "center",
borderColor: "#111",
borderRadius: 15,
borderWidth: 1,
fontSize: 16,
height: 38,
justifyContent: "center",
paddingLeft: 10,
width: 275,
},
forgotpassword: {
marginTop: 10,
textAlign: "right",
},
heading: {
color: "#C0C0C0",
paddingLeft: 25,
},
login: {
backgroundColor: "#FFB900",
borderRadius: 25,
height: 45,
marginLeft: 25,
marginRight: 15,
marginTop: 150,
position: "absolute",
right: 0,
width: 150,
},
login_caption: {
color: "#fff",
justifyContent: "center",
paddingLeft: 15,
paddingTop: 12,
textAlign: "left",
},
parent: {
marginTop: 85,
},
password: {
alignSelf: "center",
borderColor: "#111",
borderRadius: 15,
borderWidth: 1,
fontSize: 16,
height: 38,
justifyContent: "center",
marginTop: 15,
paddingLeft: 10,
width: 275,
},
root: {
alignSelf: "center",
height: 350,
marginTop: 85,
width: 250,
},
title: {
fontSize: 36,
fontWeight: "900",
paddingLeft: 25,
},
});
export default Login;
There were few mistakes in your code,
you used setErrorText without declaring it.
this line <TouchableOpacity title="Login" style={styles.login} onPress={handleSubmitPress()}> was not good, maybe it was the cause of infinite rendering.
I solved all those errors very easily by using some extension in my IDE to clean code automatically like prettier and ESLint, and I used typescript. I really suggests that you do the same.

Related

how to post array of multiple object in react native

**how to pass array of multiple object in database react native . i aslo tried axios fetch and redux but its not responding **
import React, { useState, useEffect, useLayoutEffect } from 'react';
import { StyleSheet, Text, View, FlatList, TouchableOpacity, ScrollView, Dimensions } from 'react-native';
import { MaterialCommunityIcons } from '#expo/vector-icons';
import _ from "lodash"
import ClassSectionFilter from '../singleStudentAttendance/ClassSectionFilter';
import { CheckBox } from 'react-native-elements';
import { useIsFocused } from "#react-navigation/native";
import { useRegisterTechAttendanceMutation } from '../../../services/userAuthApi';
import Toast from "react-native-toast-message";
import axios from 'axios'
const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;
const MarkAttendanceScreen = ({ navigation, route }) => {
const [columns, setColumns] = useState([
"RollNo",
"Name",
])
const [direction, setDirection] = useState('')
const [selectedColumn, setSelectedColumn] = useState('')
const [ teachers , setTeachers] = useState([]);
const [ attendance, setAttendance ] = useState()
const [ attendanceState, setAttendanceState ] = useState('')
const fetchData = async () => {
const resp = await fetch(`http://192.168.18.64:8000/api/user/getSometeacher/${route.params.schoolId}`);
const data = await resp.json();
const schAdminId = (data.map(l => l._id ? { ...l, schoolAdminID: route.params.schoolAdminID } : l));
setAttendanceState(schAdminId)
};
const focus = useIsFocused();
useLayoutEffect(()=>{
fetchData();
}, [focus])
const MarkAttendance = (item, S) => {
const attend = (attendanceState.map(l => l._id === item._id ? { ...l, attendance: S } : l));
setAttendanceState(attend)
setAttendance(attend)
}
const [items, setItems] = useState()
const sortTable = (column) => {
const newDirection = direction === "desc" ? "asc" : "desc"
const sortedData = _.orderBy(teachers, [column], [newDirection])
setSelectedColumn(column)
setDirection(newDirection)
setTeachers(sortedData)
}
const [registerTechAttendance] = useRegisterTechAttendanceMutation();
const handleFormSubmit = async () => {
const bodyFormData = new FormData();
attendance.forEach((item) => {
bodyFormData.append('attendance', item);
});
const res = axios.post('http://192.168.18.64:8000/api/user/teacherattendance', bodyFormData)
if (res.data.status === "success") {
navigation.navigate("SchoolAdminHomePage");
}
if (res.data.status === "failed") {
Toast.show({
type: "warning",
position: "top",
topOffset: 0,
text1: res.data.message,
});
}
};
// const onSubmit = () => {
// const formData = new FormData()
// formData.append(attendance);
// console.log(formData)
// fetch('http://192.168.18.64:8000/api/user/teacherattendance', {
// method: "POST",
// body: JSON.stringify(formData),
// headers: {
// 'content-type': 'application/json',
// }
// })
// .then((response) => console.log(response))
// .catch(err => {
// console.log(err);
// })
// }
const tableHeader = () => (
<View style={styles.tableHeader} >
{
columns.map((column, index) => {
{
return (
<TouchableOpacity
key={index}
style={styles.columnHeader}
onPress={() => sortTable(column)}>
<Text style={styles.columnHeaderTxt}>{column + ""}
{selectedColumn === column && <MaterialCommunityIcons
name={direction === "desc" ? "arrow-down-drop-circle" : "arrow-up-drop-circle"}
/>
}
</Text>
</TouchableOpacity>
)
}
})
}
</View>
)
return (
<View style={{ height: windowHeight, width: '100%' }}>
<View >
<ClassSectionFilter />
</View>
<FlatList
data={attendanceState}
keyExtractor={(item, index) => index + ""}
style={{ maxWidth: '100%' }}
ListHeaderComponent={tableHeader}
stickyHeaderIndices={[0]}
extraData={attendanceState}
renderItem={({ item, index }) => {
return (
<View style={{ ...styles.tableRow, backgroundColor: index % 2 == 1 ? "#F0FBFC" : "white", width: '100%', }}>
<Text style={{ ...styles.columnRowTxt, fontWeight: "bold" }}>{item.roll_no}</Text>
<Text style={{ ...styles.columnRowTxt }}>{item.first_name}</Text>
<ScrollView horizontal={true}
showsHorizontalScrollIndicator={true}
pagingEnabled={true}
style={{ width: '150%' }}
>
<View style={{ flexDirection: 'row', left: 40 }}>
<View
style={{
left: 23
}}
>
<CheckBox
title='P'
checkedColor='green'
checked={item.attendance === 'P' ? true : false}
checkedIcon="dot-circle-o"
unCheckedIcon='circle-o'
onPress={() => MarkAttendance(item, 'P')}
containerStyle={{
alignItems: 'center',
justifyContent: 'center',
height: 50,
right: 50,
alignItems: 'center',
justifyContent: 'center',
top: -10,
backgroundColor: 'transparent'
}}
/>
{/* <BouncyCheckbox
size={20}
fillColor="green"
unfillColor="#FFFFFF"
text="P"
iconStyle={{ }}
textStyle={{ }}
onPress={()=>MarkPresent()}
isChecked={false}
/> */}
</View>
<View style={{
left: 5
}}>
<CheckBox
title='A'
checkedColor='red'
checked={item.attendance === 'A' ? true : false}
checkedIcon="dot-circle-o"
unCheckedIcon='circle-o'
onPress={() => MarkAttendance(item, 'A')}
containerStyle={{
alignItems: 'center',
justifyContent: 'center',
height: 50,
right: 50,
alignItems: 'center',
justifyContent: 'center',
top: -10,
backgroundColor: 'transparent'
}}
/>
{/* <BouncyCheckbox
size={20}
fillColor="red"
unfillColor="#FFFFFF"
text="A"
iconStyle={{ }}
textStyle={{ }}
onPress={()=>MarkAbsent()}
/> */}
</View>
<View style={{
left: 5,
}}>
<CheckBox
title='L'
checkedColor='gray'
checked={item.attendance === 'L' ? true : false}
checkedIcon='dot-circle-o'
unCheckedIcon='circle-o'
onPress={() => MarkAttendance(item, 'L')}
containerStyle={{
alignItems: 'center',
justifyContent: 'center',
height: 50,
right: 70,
alignItems: 'center',
justifyContent: 'center',
top: -10,
backgroundColor: 'transparent',
}}
/>
</View>
</View>
</ScrollView>
</View>
)
}}
/>
<View>
<TouchableOpacity
onPress={handleFormSubmit}
style={{
justifyContent: "center",
alignItems: "center",
padding: 15,
width: "100%",
marginVertical: 5,
borderRadius: 50,
marginBottom: 60,
fontWeight: "bold",
backgroundColor: "#5062BD",
elevation: 1,
marginTop: 30,
bottom:20,
}}
>
<Text
style={{
color: "white",
justifyContent: "center",
alignItems: "center",
}}
>
Submit Attendance
</Text>
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
tableHeader: {
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
backgroundColor: "#5062BD",
borderTopEndRadius: 10,
borderTopStartRadius: 10,
height: 50,
},
tableRow: {
flexDirection: "row",
height: 40,
margin: 2,
left: 8
},
columnHeader: {
width: "16%",
justifyContent: "center",
alignItems: "flex-start",
margin: 10
},
columnHeaderTxt: {
color: "white",
fontWeight: "bold",
},
columnRowTxt: {
width: "18%",
}
});
export default MarkAttendanceScreen
data also show in my console but it is not posting. i am also trying redux, fetch and axios method but its not give me a solution
enter image description here

undefined TypeError: Cannot read properties of undefined (reading 'path')

routes.js
const storage = multer.diskStorage({
destination: "./Upload/Images",
filename: (req, file, cb) => {
return cb(
null,
//file.originalname
`${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
//`${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`
);
},
});
const upload = multer({
storage: storage,
limits: {
fileSize: 900000,
},
});
petRoute.route("/addpets").post(upload.single("imgforsell"), (req, res) => {
console.log(req.file);
var img = fs.readFileSync(req.file.path);
//var img = fs.readFileSync(req.body.path);
var encode_image = img.toString("base64");
const pet = new petModel({
name: req.body.name,
title: req.body.title,
contact: req.body.contact,
price: req.body.price,
description: req.body.description,
selectedcat: req.body.selectedcat,
selectedcity: req.body.selectedcity,
imgforsell: Buffer.from(encode_image, "base64"),
//imgforsell:req.body.imgforsell,
contentType: req.file.mimetype,
});
pet
.save() // img
.then((img) => {
//img.id
res.json(img.id);
})
.catch((err) => {
//remove return and curly braces
return res.json(err);
});
});
I am trying to build a mern stack application using React-native expo.In this application I am trying to store an image as buffer data in mongo database which stores image name as binary format mongodb and I mage is being upload to static folder in root folder.This above code work fine with Postman but when I try to add data with Physical device it give two error on backend:
undefined
TypeError: Cannot read properties of undefined (reading 'path')
on Frontend:
Request failed with status code 500
I am using axios to post data
frontend.js
import {
View,
Text,
TextInput,
Image,
TouchableOpacity,
StyleSheet,
ScrollView,
Picker,
Platform,
Alert,
input
} from "react-native";
//const bodyParser = require('body-parser')
//router.use(bodyParser.json());
//router.use(bodyParser.urlencoded({ extended: true }));
import React, { Component } from "react";
import axios from "axios";
import * as ImagePicker from 'expo-image-picker';
import ImagePickerExample from "../components/CameraFunc";
import Constants from "expo-constants";
import * as FileSystem from 'expo-file-system';
export default class Sellnow extends Component {
constructor(props) {
super(props);
this.onChangePetName = this.onChangePetName.bind(this);
this.onChangePetTitle = this.onChangePetTitle.bind(this);
this.onChangePetContact = this.onChangePetContact.bind(this);
this.onChangePetPrice = this.onChangePetPrice.bind(this);
this.onChangePetDescription = this.onChangePetDescription.bind(this);
this.onValueChangeCat= this.onValueChangeCat.bind(this);
this.onValueChangeCity= this.onValueChangeCity.bind(this);
this.onFileChange = this.onFileChange.bind(this);
// this.pickImage = this.pickImage.bind(this);
this.onSubmit = this.onSubmit.bind(this);
// State
this.state = {
name: "",
title: "",
contact: "",
price: "",
description: "",
selectedcat:"",
selectedcity:"",
imgforsell:"",
//collection categories
category: [
{
itemName: "Select Category...."
},
{
itemName: "Pets Food"
},
{
itemName: "Pets Products"
},
{
itemName: "Pets Accessories"
}
],
// cities category
cityCategory:[
{
itemName: "Select City...."
},
{
itemName: "Islamabad"
},
{
itemName: "Rawalpindi"
},
{
itemName: "Lahore"
},
{
itemName: "Peshawar"
},
{
itemName: "Karachi"
},
{
itemName: "Quetta"
}
]
};
}
/*componentDidMount() {
axios.get('http://localhost:3000/PetsBazar/pets/' )
.then(res => {
this.setState({
name: res.data.name,
title: res.data.title,
contact: res.data.contact
});
})
.catch((error) => {
console.log(error);
})
}*/
onChangePetName(e) {
this.setState({ name: e.target.value });
}
onChangePetTitle(e) {
this.setState({ title: e.target.value });
}
onChangePetContact(e) {
this.setState({ contact: e.target.value });
}
onChangePetPrice(e) {
this.setState({ price: e.target.value });
}
onChangePetDescription(e) {
this.setState({ description: e.target.value });
}
// categories function
onValueChangeCat(e) {
this.setState({ selectedcat: e.targetvalue })
}
// city function
onValueChangeCity(e) {
this.setState({ selectedcity: e.targetvalue })
}
onFileChange(e) {
this.setState({ imgforsell: e.target.files[0] })}
// uploading Image
_getPhotoLibrary = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
allowsEditing: true,
base64: true,
exif: true,
aspect: [4, 3]
});
if (!result.cancelled) {
this.setState({ imgforsell: result });
}
this.props.navigation.setParams({
imgforsell: this.state.imgforsell
});
};
onSubmit (e) {
e.preventDefault();
/*const petsObject = {
name: this.state.name,
title: this.state.title,
contact: this.state.contact,
price: this.state.price,
description: this.state.description,
selectedcat:this.state.selectedcat,
selectedcity:this.state.selectedcity,
imgforsell:this.state.imgforsell
};
*/
const formData = new FormData();
/*formData.append( 'imgforsell', {
// name: new Date() + '_profile',
uri: this.state.imgforsell,
type: 'image/jpg',
});*/
formData.append("name", this.state.name);
formData.append("title", this.state.title);
formData.append("contact", this.state.contact);
formData.append("price", this.state.price);
formData.append("description", this.state.description);
formData.append("selectedcat", this.state.selectedcat);
formData.append("selectedcity", this.state.selectedcity);
formData.append("imgforsell", this.state.imgforsell);
fetch(
`http://${
Platform.OS === "android" ? "192.168.10.11" : "localhost"
}:4000/pets/addpets`,
{
method: "POST",
body: formData,
}
)
.then((res) => {
if (!res.ok) {
return Promise.reject(res);
}
return res.json();
})
.then((data) => {
console.log(data);
})
.catch((err) => {
console.error(err);
})
.finally(() => {
this.setState({
name: "",
title: "",
contact: "",
price: "",
description: "",
selectedcat: "",
selectedcity: "",
imgforsell: "",
});
});
}
render() {
const {imgforsell} = this.state
return (
<View>
<ScrollView
nestedScrollEnabled={true}
showsVerticalScrollIndicator={false}
>
<View style={styles.container}>
<View style={styles.formContainer}>
<Text style={styles.conText}>Please Fill the Below Form </Text>
<View style={styles.borderForm}>
<Text style={styles.formText}>Your Name</Text>
<TextInput
style={styles.formInput}
multiline
placeholder="Please Enter Your Name"
maxLength={15}
value={this.state.name}
onChange={this.onChangePetName}
blurOnSubmit={true}
onChangeText={(name) => this.setState({ name })}
/>
<Text style={styles.formText}>Category</Text>
{ /*<CategoryDropList />*/ }
<View style={styles.viewStyle}>
<Picker
itemStyle={styles.itemStyle}
mode="dropdown"
style={styles.pickerStyle}
selectedValue={this.state.selectedcat}
// onValueChange={this.onValueChangeCat.bind(this)}
//onValueChange={(selectedcat)=>this.setState({selectedcat})}
onValueChange={(itemValue,itemIndex)=> this.setState({selectedcat:itemValue})}
>
{this.state.category.map((item, index) => (
<Picker.Item
color="black"
label={item.itemName}
value={item.itemName}
index={index}
/>
))}
</Picker>
</View>
<Text style={styles.formText}>Pet/Product Title</Text>
<TextInput
style={styles.formInput}
placeholder="Enter Product Title"
maxLength={15}
value={this.state.title}
blurOnSubmit={true}
onChange={this.onChangePetTitle}
onChangeText={(title) => this.setState({ title })}
/>
<Text style={styles.formText}>City</Text>
{/*<CityDropList />*/}
<View style={styles.viewStyle}>
<Picker
itemStyle={styles.itemStyle}
mode="dropdown"
style={styles.pickerStyle}
selectedValue={this.state.selectedcity}
onValueChange={(itemValue,itemIndex)=> this.setState({selectedcity:itemValue})}
>
{this.state.cityCategory.map((item, index) => (
<Picker.Item
color="black"
label={item.itemName}
value={item.itemName}
index={index}
/>
))}
</Picker>
</View>
<Text style={styles.formText}> Contact Number </Text>
<TextInput
style={styles.formInput}
placeholder="Phone Number"
inputType="number"
maxLength={11}
keyboardType="number-pad"
blurOnSubmit={true}
value={this.state.contact}
onChange={this.onChangePetContact}
onChangeText={(contact) => this.setState({ contact })}
/>
<Text style={styles.formText}>Price</Text>
<TextInput
style={styles.formInput}
multiline
placeholder="Enter Price"
inputType="number"
keyboardType="number-pad"
blurOnSubmit={true}
maxLength={7}
value={this.state.price}
onChange={this.onChangePetPrice}
onChangeText={(price) => this.setState({ price })}
/>
<Text style={styles.formText}>Image of Product</Text>
{/*<ImagePickerExample />*/}
<TouchableOpacity style={styles.btn} onPress={this._getPhotoLibrary.bind(this)}>
<Text style={styles.btnTxt}> Choose File</Text>
</TouchableOpacity>
{imgforsell ? (
<Image source={{ uri: imgforsell.uri }} style={styles.uploadimgstyle} />
) : (
<View/>
)}
<Text style={styles.formText}>
Description(Optional max 150 words)
</Text>
<TextInput
style={styles.descriptionInput}
multiline
placeholder="Describe your product"
maxLength={150}
blurOnSubmit={true}
value={this.state.description}
onChange={this.onChangePetDescription}
onChangeText={(description) => this.setState({ description })}
/>
<TouchableOpacity style={styles.btn} onPress={this.onSubmit}>
<Text style={styles.btnTxt}>Submit</Text>
</TouchableOpacity>
</View>
</View>
</View>
</ScrollView>
</View>
);
}
}
//export default withRouter(Sellnow);
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "column",
height: "auto",
width: "auto",
},
sellText: {
fontSize: 35,
fontWeight: "bold",
textAlign: "center",
},
formContainer: {
backgroundColor: "#ff9933",
flex: 1,
flexDirection: "column",
alignSelf: "center",
},
conText: {
fontSize: 25,
fontWeight: "bold",
textAlign: "left",
marginVertical: 10,
marginHorizontal: 15,
},
formInput: {
//flex:1,
height: 50,
// marginLeft:7,
//marginRight:7,
fontSize: 18,
margin: 10,
width: 350,
borderWidth: 1,
borderColor: "black",
backgroundColor: "white",
textAlign: "left",
borderRadius: 10,
padding: 10,
},
formText: {
fontSize: 20,
fontWeight: "bold",
textAlign: "left",
margin: 10,
},
descriptionInput: {
height: 80,
margin: 10,
width: 340,
borderWidth: 1,
borderColor: "black",
backgroundColor: "white",
textAlign: "left",
borderRadius: 20,
padding: 10,
},
borderForm: {
alignSelf: "center",
borderWidth: 1,
borderColor: "#FF642E",
margin: 7,
height: "auto",
width: "auto",
},
btn: {
margin: 20,
height: 35,
width: 120,
backgroundColor: "#FF642E",
borderRadius: 20,
alignSelf: "center",
},
btnTxt: {
fontSize: 20,
fontWeight: "bold",
textAlign: "center",
color: "white",
margin: 5,
},
dropdown: {
backgroundColor: "white",
borderWidth: 1,
borderColor: "black",
},
dropdownContainer: {
flex: 1,
flexDirection: "row",
flexWrap: "wrap",
alignSelf: "center",
justifyContent: "center",
paddingTop: Constants.statusBarHeight,
backgroundColor: "#ff9933",
padding: 8,
},
itemStyle: {
fontSize: 10,
fontFamily: "Roboto-Regular",
color: "black",
},
pickerStyle: {
width: "73%",
height: 40,
color: "black",
fontSize: 14,
fontFamily: "Roboto-Regular",
//marginLeft:-100,
// alignItems:"flex-start"
},
textStyle: {
fontSize: 14,
fontFamily: "Roboto-Regular",
textAlign:'left'
},
viewStyle: {
// flex: 1,
alignSelf: "center",
flexDirection: "row",
width: "140%",
justifyContent: "space-between",
alignItems: "flex-start",
borderWidth:1,
height:'5%',
backgroundColor:'white',
borderRadius:10,
margin:7
},
uploadimgstyle:{
width: 100,
height: 100,
margin:5,
resizeMode:'cover',
alignSelf:'center'
}
});
The way you're calling Axios is the problem. The signature for the post method is
axios.post(url[, data[, config]])
With your code, that's
axios.post(
/* url */ Platform.OS === "android" ? "http://192.168.10.11:4000/pets/addpets" : "http://localhost:4000/pets/addpets",
/* data */ petsObject,
/* config */ formData
)
so you're passing the FormData as the config object.
You cannot mix application/json and multipart/form-data in the same request. Instead, you need to build up FormData with all the parameters you need. When uploading a file, you also need to append the File instance and not an object with uri and type properties.
const formData = new FormData();
// append the File
formData.append("imgforsell", this.state.imgforsell);
// append other data
formData.append("name", this.state.name);
formData.append("title", this.state.title);
// etc...
axios
.post(
`http://${
Platform.OS === "android" ? "192.168.10.11" : "localhost"
}:4000/pets/addpets`,
formData
)
.then(({ data }) => {
console.log(data);
})
.catch((err) => {
console.error(err.toJSON());
// res.status(500).json(err) 👈 don't do this, it's not Express
})
.finally(() => {
this.setState({
name: "",
title: "",
contact: "",
price: "",
description: "",
selectedcat: "",
selectedcity: "",
imgforsell: "",
});
});
If Axios doesn't work (because I've seen patchy reports about file uploads in React Native), you can substitute it with fetch
fetch(
`http://${
Platform.OS === "android" ? "192.168.10.11" : "localhost"
}:4000/pets/addpets`,
{
method: "POST",
body: formData,
}
)
.then((res) => {
if (!res.ok) {
return Promise.reject(res);
}
return res.json();
})
.then((data) => {
console.log(data);
})
.catch((err) => {
console.error(err);
})
.finally(() => {
this.setState({
name: "",
title: "",
contact: "",
price: "",
description: "",
selectedcat: "",
selectedcity: "",
imgforsell: "",
});
});

How to solve the API issue giving the 400 error, react?

I am working on my react project and trying to add a page. All of the model, controller and routes have been set. But the data of the form(from my newly added page) is not posting the data into mongodb collection. I have also created the API.. But the data is not being posted
I think there is an issue with the created API it is giving the 400 error.. Please have a look of my code I am not getting the actual reason behind. Here is the code
here is my api-contactUs.js file
const create = (contactUs) => {
return fetch('/api/contactUs', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(contactUs)
})
.then((response) => {
return response.json()
}).catch((err) => console.log(err))
}
export default create
My contactUs.js file
import React from 'react';
import PropTypes from 'prop-types'
import {withStyles} from 'material-ui/styles'
import Card, {CardActions, CardContent} from 'material-ui/Card'
import Icon from 'material-ui/Icon'
import Button from 'material-ui/Button'
import TextField from 'material-ui/TextField'
import Typography from 'material-ui/Typography'
import create from './api-contactUs.js'
import { Grid } from 'material-ui';
import Dialog, {DialogActions, DialogContent, DialogContentText, DialogTitle} from 'material-ui/Dialog'
const styles = theme => ({
contactWrapper :{
backgroundImage: `url(${require('../assets/images/contactmain.svg')})`,
backgroundSize: 'cover',
backgroundPosition: '50%',
height: '115vh',
backgroundRepeat: 'no-repeat'
},
mycontainer:{
display: 'flex',
flexDirection: 'row',
flexWrap: 'wrap',
width: '100%',
justifyContent: 'center',
alignItems: 'center',
fontFamily: 'Helvetica,sans-serif'
},
contactHeader:{
padding: '20px 15px',
textAlign: 'left',
},
logo:{
width: '150px',
height: '100%'
},
contactDes:{
padding: '0 15px',
margin: '80px 0 100px',
flexDirection: 'column',
display: 'flex',
alignItems: 'center',
'& h1': {
fontSize: '40px',
lineHeight: '50px',
margin: '0 0 30px',
fontFamily: 'Canela Deck Bold !important',
color: '#21d192',
fontWeight: '600',
'& span':{
color: '#fff',
display: 'block'
}
},
'& p':{
color: '#fff',
fontSize: '14px',
letterSpacing: '.8px',
lineHeight: '21px',
margin: '0 0 30px',
display: 'block',
fontFamily: 'inherit',
},
'& ul':{
color: '#fff',
fontSize: '14px',
letterSpacing: '.8px',
lineHeight: '22px',
paddingLeft: '15px',
margin: '0',
fontFamily: 'inherit',
'& li':{
marginBottom: '10px'
}
}
},
contactForm: {
flexDirection: 'column',
display: 'flex',
alignItems: 'center'
},
card:{
minWidth: '520px',
maxWidth: '520px',
},
error: {
verticalAlign: 'middle'
},
textField:{
width: 454,
},
typography:{
margin: '30px 0 20px',
textAlign: 'center !important',
fontSize: '17px',
lineHeight: '24px',
fontWeight: '500',
color: 'rgb(34, 34, 34)',
fontFamily: 'inherit',
color: '#222',
fontStyle: 'oblique'
},
submit:{
margin: 'auto',
marginBottom: theme.spacing.unit * 4
}
})
class ContactUs extends React.Component {
state = {
fname: '',
lname: '',
email: '',
phone_no: '',
description: '',
open: false,
error: ''
}
handleChange = name => event => {
this.setState({[name]: event.target.value})
}
clickSubmit = () => {
const contactUs = {
name: this.state.fname || undefined,
name: this.state.lname || undefined,
email: this.state.email || undefined,
phone_no: this.state.phone_no || undefined,
description: this.state.description || undefined,
}
create(contactUs).then((data) => {
if (data.error) {
this.setState({error: data.error})
} else {
this.setState({error: '', open: true})
}
})
}
render(){
const {classes} = this.props;
return(
<div className={classes.contactWrapper}>
<Grid >
<Grid container item xs={12} className={classes.contactHeader}><img className={classes.logo} src={require('../assets/images/Main_logo.svg')}/></Grid>
<Grid item md={12} className={classes.mycontainer}>
<Grid item md={6} sm={12} className={classes.contactDes}>
<div style={{minWidth: '520px', maxWidth: '520px'}}>
<h1> Get the Local Services
<span>you need!</span>
</h1>
<p>Professional Services is the top local services providing app, helping you to provide services faster and more efficiently. Our services providing, Professional Services Platform, can help you:</p>
<ul>
<li>Find the best talent with the support of a dedicated account manager.</li>
<li>Find the best talent with the support of a dedicated.</li>
<li>Find the best talent with the support.</li>
</ul>
</div>
</Grid>
<Grid item md={6} sm={12} className={classes.contactForm}>
<Card className={classes.card}>
<CardContent style={{width: '470px'}}>
<Typography className={classes.typography}>For any complaint or query, fill this out and we’ll contact you, as soon as possible.</Typography>
<TextField id="fname" name="fname" label="First Name" value={this.state.fname} onChange={this.handleChange('fname')} className={classes.textField} margin="normal"/><br/>
<TextField id="lname" name="lname" label="Last Name" value={this.state.lname} onChange={this.handleChange('lname')} className={classes.textField} margin="normal"/><br/>
<TextField id="email" name="email" type="email" label="Business Email" value={this.state.email} onChange={this.handleChange('email')} className={classes.textField} margin="normal"/><br/>
<TextField id="phone_no" name="phone_no" label="Phone Number" value={this.state.phone_no} onChange={this.handleChange('phone_no')} className={classes.textField} margin="normal"/><br/>
<TextField
id="multiline-flexible"
label="Post your request"
multiline
row="2"
value={this.state.description}
onChange={this.handleChange('description')}
className={classes.textField}
margin="normal"
/><br/>
{
this.state.error && (<Typography component="p" color="error">
<Icon color="error" className={classes.error}>error</Icon>
{this.state.error}</Typography>)
}
<br /><br />
</CardContent>
<CardActions>
<Button color="secondary" variant="raised" onClick={this.clickSubmit} className={classes.submit}>Submit</Button>
<br />
</CardActions>
</Card>
<Dialog open={this.state.open} disableBackdropClick={true}>
<DialogTitle>Request</DialogTitle>
<DialogContent>
<DialogContentText>
Your Request is registerd!
</DialogContentText>
</DialogContent>
{/* <DialogActions>
<Link to="/signin">
<Button color="primary" autoFocus="autoFocus" variant="raised">
Sign In
</Button>
</Link>
</DialogActions> */}
</Dialog>
</Grid>
</Grid>
</Grid>
</div>
);
}
}
ContactUs.propTypes = {
classes: PropTypes.object.isRequired
}
export default withStyles(styles)(ContactUs);
contactUs.controller.js file
import Contact from '../models/contactUs.model'
import _ from 'lodash'
import errorHandler from '../helpers/dbErrorHandler'
const create = (req, res, next) => {
const contact = new Contact(req.body)
contact.save((err, result) => {
if (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
res.status(200).json({
message: "You Complained Successfully!"
})
})
}
export default create
contactUs.routes.js file
import express from 'express'
import contactUsCtrl from '../controllers/contactUs.controller'
const router = express.Router()
router.route('/api/contactUs/')
.post(contactUsCtrl)
export default router
contactUs.model.js file
import mongoose from 'mongoose'
import crypto from 'crypto'
const ContactSchema = new mongoose.Schema({
fname: {
type: String,
trim: true,
required: 'First Name is required'
},
lname: {
type: String,
trim: true,
},
email: {
type: String,
trim: true,
match: [/.+\#.+\..+/, 'Please fill a valid email address'],
required: 'Email is required'
},
phone_no: {
type: String,
trim: true,
required: 'Phone no is required'
},
description: {
type: String,
trim: true,
required: 'Submit the reason'
}
}
)
export default mongoose.model('Contact', ContactSchema)
Looking forward:)
You have not provided any error messages, but I think the problem is in your clickSubmit method, where in contactUs object, you have field "name" set up twice, instead of having fname and lname.

react native if else condition in render()

Hello everyone i am learning REACT-NATIVE from last two months , i got a small issue with if-else condition render method ,while i am executing the code if condition is not working properly .
Can you please tell me the solution
import React, { Component } from 'react';
import {
Image, Platform, StyleSheet, Text, View, TextInput, Button, TouchableHighlight, Alert,
TouchableOpacity, ScrollView, ColorPropType, FlatList, SectionList, Dimensions, AsyncStorage,
Keyboard,
} from 'react-native';
import axios from 'axios';
import GlobalStore from '../GlobalStore';
const API_URL = GlobalStore.BASE_URL;
var ACCESS_TOKEN = 'access_token';
export default class LogInScreen extends React.Component {
static navigationOptions = {
title: 'LogIn',
headerStyle: {
backgroundColor: '#03A9F4',
},
headerTintColor: '#fff',
headerTitleStyle: {
fontWeight: 'bold',
},
};
/* *********** Code Starts Here ****************** */
constructor(props) {
super(props);
this.state = {
error: '',
userId: '',
user_id: '',
mobile: '',
password: '',
Token: '',
};
}
componentDidMount() {
this.get_Id();
this.getToken();
}
// get id from asyncStorage
async get_Id() {
try {
const userId = await AsyncStorage.getItem('USER_ID') // (STORAGE_KEY)
if (userId !== '' || userId !== null) {
this.setState({ userId: userId })
console.log('profile get_id id: =>', userId)
// this.getUserDetails(userId)
} else {
console.log('profile get_id id: => user_id=null')
Alert.alert('No user profile found LogIn Now ' + this.props.navigation.navigate('LogIn'))
}
} catch (error) {
alert('Failed to load profile get_Id() user_id.')
}
}
async storeToken(accessToken) {
try {
await AsyncStorage.setItem(ACCESS_TOKEN, accessToken);
this.getToken();
} catch (error) {
console.log('LogIn AsyncStorage Error: ' + error.message);
}
}
async getToken() {
try {
let token = await AsyncStorage.getItem(ACCESS_TOKEN);
this.setState({ Token: token })
console.log("LogIn Get token is :" + token);
} catch (error) {
console.log("something went wrong in getToken LogIn page")
}
}
async removeToken() {
try {
await AsyncStorage.removeItem(ACCESS_TOKEN);
this.getToken();
} catch (error) {
console.log("some thing went wrong removeToken LogIn page")
}
}
validate_Fields = () => {
const { mobile, password } = this.state
if (mobile == "") {
Alert.alert("please enter Mobile Number");
return false
}
if (mobile.length < 10) {
Alert.alert("please enter 10 digit Mobile Number");
return false
}
if ((password === "" && password.length < 6)) {
Alert.alert("please enter password minimum length should be 6");
return false
}
return true
}
// logIn function
logInUser() {
if (this.validate_Fields()) {
const { mobile, password } = this.state;
this.setState({ error: '', loading: true });
// NOTE HTTP is insecure, only post to HTTPS in production apps
axios.post(API_URL + '/usersapi/user_LogIn', {
mobile_no: mobile,
password: password
})
.then((response) => {
// console.log(JSON.stringify(response));
let accessToken = response.data.TOKEN;
this.storeToken(accessToken);
console.log("dataToken-LogIn:" + accessToken);
Alert.alert('LogIn Successfully ' + this.props.navigation.navigate('Profile', { accessToken }));
// Alert.alert('LogIn Successfully ' + + this.props.navigation.navigate('Profile'));
})
.catch((error) => {
console.log(error);
this.removeToken();
Alert.alert(' Login Failed try again , If you do not have an account, sign up first !');
});
}
}
render() {
if (this.state.userId !== '' || this.state.userId !== null) {
return (
// console.log('if block - No data found profile => LogIn now.:' + this.state.userId)
// Alert.alert('Please LogIn Now')
<View style={styles.container}>
<View style={styles.ifContainer}>
<Text style={styles.formHeader}>Thank you - you are already logedIn Got to</Text>
<TouchableOpacity style={[styles.buttonContainer, styles.greenButton]} onPress={() => this.props.navigation.navigate('Home')}>
<Text style={styles.buttonText}>Home</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.buttonContainer, styles.blueButton]} onPress={() => this.props.navigation.navigate('Profile')}>
<Text style={styles.buttonText}>Profile</Text>
</TouchableOpacity>
</View>
</View>
// Alert.alert('You are already LogedIn ' + this.props.navigation.navigate('Profile'))
)
} else {
return (
<View styel={styles.container}>
<View style={{ alignItems: 'center', justifyContent: 'center' }}>
<Text style={styles.formHeader}>LogIn</Text>
<View style={styles.inputContainer}>
<TextInput style={styles.inputs}
type='number'
value={this.state.mobile}
name="mobile"
maxLength={10}
placeholder="mobile"
keyboardType="numeric"
underlineColorAndroid='transparent'
onChangeText={(mobile) => this.setState({ mobile })} />
<Image style={styles.inputIcon} source={{ uri: 'https://img.icons8.com/color/48/000000/android.png' }} />
</View>
<View style={styles.inputContainer}>
<TextInput style={styles.inputs}
type='password'
value={this.state.password}
name="password"
placeholder="Password"
secureTextEntry={true}
underlineColorAndroid='transparent'
onChangeText={(password) => this.setState({ password })} />
<Image style={styles.inputIcon} source={{ uri: 'https://img.icons8.com/color/40/000000/password.png' }} />
</View>
<TouchableOpacity style={[styles.buttonContainer, styles.greenButton]} onPress={() => { this.logInUser() }}>
<Text style={styles.buttonText}>LogIn</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.buttonContainer, styles.blueButton]} onPress={() => this.props.navigation.navigate('Register')}>
<Text style={styles.buttonText}>Register</Text>
</TouchableOpacity>
</View >
</View>
)
}
}// Render Ends
} // Class Ends
const resizeMode = 'center';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#DCDCDC',
},
formHeader: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom: 20,
fontSize: 30,
backgroundColor: 'transparent',
color: 'black',
},
inputContainer: {
borderBottomColor: '#F5FCFF',
backgroundColor: '#FFFFFF',
borderRadius: 30,
borderBottomWidth: 1,
width: 300,
height: 45,
marginBottom: 20,
flexDirection: 'row',
alignItems: 'center',
shadowColor: "#808080",
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5,
},
inputs: {
height: 45,
marginLeft: 16,
borderBottomColor: '#FFFFFF',
flex: 1,
fontSize: 20,
},
inputIcon: {
width: 30,
height: 30,
marginRight: 15,
justifyContent: 'center'
},
buttonContainer: {
height: 45,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom: 20,
width: 300,
borderRadius: 30,
backgroundColor: 'transparent'
},
greenButton: {
backgroundColor: "#00a63f",
shadowColor: "#808080",
shadowOffset: {
width: 0,
height: 9,
},
shadowOpacity: 0.50,
shadowRadius: 12.35,
elevation: 19,
},
blueButton: {
backgroundColor: "#4e8bd1",
shadowColor: "#808080",
shadowOffset: {
width: 0,
height: 9,
},
shadowOpacity: 0.50,
shadowRadius: 12.35,
elevation: 19,
},
buttonText: {
color: 'white',
fontSize: 20,
fontWeight: 'bold',
textShadowColor: 'rgba(0, 0, 0, 0.75)',
textShadowOffset: { width: -1, height: 1 },
textShadowRadius: 10
},
bgImage: {
flex: 1,
resizeMode,
position: 'absolute',
width: '100%',
height: '100%',
justifyContent: 'center',
}
});
LogInScreen.navigationOptions = {
title: 'LogIn',
};
please check the code and let me know if i wrote anything wrong in the code .
change if condition in render from or to and:
if (this.state.userId !== '' && this.state.userId !== null) {....}
Recommended: Change method get_Id to arrow function signature:
get_Id = async ()=> {
try {
const userId = await AsyncStorage.getItem('USER_ID') // (STORAGE_KEY)
if (userId !== '' || userId !== null) {
this.setState({ userId: userId })
console.log('profile get_id id: =>', userId)
// this.getUserDetails(userId)
} else {
console.log('profile get_id id: => user_id=null')
Alert.alert('No user profile found LogIn Now ' + this.props.navigation.navigate('LogIn'))
}
} catch (error) {
alert('Failed to load profile get_Id() user_id.')
}
}

How to hide Material-Ui Mini variant Drawer on mobile view

How can I hide Mini variant drawer on mobile view. I don't want the side bar on mobile view. It should be hidden in mobile view.
I am following the official doc Original Code
Remove in mobile View
change styles to do it:
drawerPaperClose: {
overflowX: 'hidden',
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
width: theme.spacing.unit * 7,
[theme.breakpoints.up('sm')]: {
width: theme.spacing.unit * 9,
},
[theme.breakpoints.down('sm')]: {
width: 0,
display:'none',
},
},
nested: {
paddingLeft: theme.spacing.unit * 4,
},
const drawerWidth = 240;
const styles = theme => ({
root: {
display: 'flex',
},
toolbar: {
paddingRight: 24, // keep right padding when drawer closed
},
toolbarIcon: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
padding: '0 8px',
...theme.mixins.toolbar,
},
appBar: {
zIndex: theme.zIndex.drawer + 1,
transition: theme.transitions.create(['width', 'margin'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
appBarShift: {
marginLeft: drawerWidth,
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(['width', 'margin'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen,
}),
},
menuButton: {
marginLeft: 12,
marginRight: 36,
},
menuButtonHidden: {
display: 'none',
},
title: {
flexGrow: 1,
},
drawerPaper: {
position: 'relative',
whiteSpace: 'nowrap',
width: drawerWidth,
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen,
}),
[theme.breakpoints.up('md')]: {
position: 'relative',
},
},
drawerPaperClose: {
overflowX: 'hidden',
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
width: theme.spacing.unit * 7,
[theme.breakpoints.up('sm')]: {
width: theme.spacing.unit * 9,
},
},
appBarSpacer: theme.mixins.toolbar,
content: {
flexGrow: 1,
padding: theme.spacing.unit * 3,
height: '100vh',
overflow: 'auto',
},
chartContainer: {
marginLeft: -22,
},
tableContainer: {
height: 320,
},
});
class Dashboard extends React.Component {
state = {
open: false,
auth: true,
anchorEl: null,
};
handleDrawerOpen = () => {
this.setState({ open: true });
};
handleDrawerClose = () => {
this.setState({ open: false });
};
handleChange = event => {
this.setState({ auth: event.target.checked });
};
handleMenu = event => {
this.setState({ anchorEl: event.currentTarget });
};
handleClose = () => {
this.setState({ anchorEl: null });
};
render() {
const { classes, siteTitle, children,theme } = this.props;
const { auth, anchorEl } = this.state;
const open = Boolean(anchorEl);
return (
<React.Fragment>
<CssBaseline />
<div className={classes.root}>
<AppBar
position="absolute"
className={classNames(classes.appBar, this.state.open && classes.appBarShift)}
style={{ background: '#051745', boxShadow: 'none' }}
>
<Toolbar disableGutters={!this.state.open} className={classes.toolbar}>
<IconButton
color="inherit"
aria-label="Open drawer"
onClick={this.handleDrawerOpen}
className={classNames(
classes.menuButton,
this.state.open && classes.menuButtonHidden,
)}
>
<MenuIcon />
</IconButton>
<Typography variant="title" color="inherit" noWrap className={classes.title}>
{siteTitle}
</Typography>
<IconButton color="inherit">
<Badge badgeContent={4} color="secondary">
<NotificationsIcon />
</Badge>
</IconButton>
<div>
<IconButton
aria-owns={open ? 'menu-appbar' : null}
aria-haspopup="true"
onClick={this.handleMenu}
color="inherit"
>
<AccountCircle />
</IconButton>
<Menu
id="menu-appbar"
anchorEl={anchorEl}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={open}
onClose={this.handleClose}
>
<MenuItem onClick={this.handleClose}>Profile</MenuItem>
<MenuItem onClick={this.handleClose}>My account</MenuItem>
</Menu>
</div>
</Toolbar>
</AppBar>
<Hidden mdUp>
<Drawer
variant="temporary"
onClose={this.handleDrawerClose}
classes={{
paper: classNames(classes.drawerPaper, !this.state.open && classes.drawerPaperClose),
}}
ModalProps={{
keepMounted: true, // Better open performance on mobile.
}}
open={this.state.open}
>
<div className={classes.toolbarIcon}>
{siteTitle}
<IconButton onClick={this.handleDrawerClose}>
<ChevronLeftIcon />
</IconButton>
</div>
<Divider />
<List >{mainListItems}</List>
<Divider />
<List>{secondaryListItems}</List>
</Drawer>
</Hidden>
<Hidden smDown implementation="css">
<Drawer
variant="permanent"
classes={{
paper: classNames(classes.drawerPaper, !this.state.open && classes.drawerPaperClose),
}}
open={this.state.open}
>
<div className={classes.toolbarIcon}>
{siteTitle}
<IconButton onClick={this.handleDrawerClose}>
<ChevronLeftIcon />
</IconButton>
</div>
<Divider />
<List >{mainListItems}</List>
<Divider />
<List>{secondaryListItems}</List>
</Drawer>
</Hidden>
<main className={classes.content} >
<div className={classes.appBarSpacer} />
{children}
<Footer />
</main>
</div>
</React.Fragment>
);
}
}
Dashboard.propTypes = {
classes: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
};
export default withStyles(styles)(Dashboard);
All you need to do is change the styles of th drawerClose object.
THE CODE IN THE DOCUMENTATION
drawerClose: {
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
overflowX: 'hidden',
width: theme.spacing(7) + 1,
[theme.breakpoints.up('sm')]: {
width: theme.spacing(9) + 1,
},
[theme.breakpoints.down('sm')]: {
width: theme.spacing(0) + 1,
},
},
The below is the new code, where you update the breakpoints by adding the .down('sm') method. Which modifies the styles for all screens below the specified 'sm' breakpoints.
[theme.breakpoints.down('sm')]: {
width: theme.spacing(0) + 1,
},
THE NEW UPDATED CODE:
drawerClose: {
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
overflowX: 'hidden',
width: theme.spacing(7) + 1,
[theme.breakpoints.up('sm')]: {
width: theme.spacing(9) + 1,
},
// New Code.
[theme.breakpoints.down('sm')]: {
width: theme.spacing(0) + 1,
},
},

Resources