error using datalisting react-redux-datatable package - node.js

In the view I put all code for datatable and also using react redux method ,when I run this code then give me error look like this :
Your render method should have return statement
react/require-render-return
How to fix it?
service.js file
import React, { Component } from 'react';
import DataTable from 'react-redux-datatable';
import 'react-redux-datatable/dist/styles.css';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom';
import {Link} from 'react-router-dom';
import {getServices} from '../../actions/servicesActions';
import Spinner from '../Spinner';
class Services extends Component{
componentDidMount(){
const api= this.props.getServices();
}
render(){
const services=this.props.services;
var tableSettings = {
tableID: 'AdvancedFeaturesTable',
wrapperType: 'section',
displayTitle: 'Requests Table',
keyField: '_id',
defaultSort: ['_id', 'desc'],
minWidth: 880,
useLocalStorage: true,
tableColumns: [
{
title: '_id',
key: '_id',
width: 90,
},
{
title: 'Name',
key: 'name',
width: 90,
},
{
title: 'Description',
key: 'description',
width: 90,
},
{
title: 'Status',
key: 'status',
width: 164,
},
{
title: 'Subscription',
key: 'subscription',
width: 90,
},
],
};
var DataTable = () => (
<DataTable
tableSettings={tableSettings}
apiLocation={services}
/>
)
}
};
const mapStateToProps = state => {
return {
service: state.services.service
};
};
export default connect(
mapStateToProps,
{
getServices
}
)(Services);
getservices.js
export const getServices=() =>dispatch => {
dispatch(setLoading());
axios.get('/api/admin/services')
.then(res =>
dispatch({
type:GET_SERVICES,
payload:res.data
})
)
.catch(err =>
dispatch({
type: GET_SERVICES,
payload: {}
})
)
}
error display
Line 199: Your render method should have return statement react/require-render-return
referral link
https://www.npmjs.com/package/react-redux-datatable

The error is clear. A component in react must return a jsx element or set of jsx elements.
In your Services component the render method isn’t returning anything
Looks like you want Services component to render DataTable so replace below code in your Services component render
render(){
const tableSettings = {
tableID: 'AdvancedFeaturesTable',
wrapperType: 'section',
displayTitle: 'Requests Table',
keyField: '_id',
defaultSort: ['_id', 'desc'],
minWidth: 880,
useLocalStorage: true,
tableColumns: [
{
title: '_id',
key: '_id',
width: 90,
},
{
title: 'Name',
key: 'name',
width: 90,
},
{
title: 'Description',
key: 'description',
width: 90,
},
{
title: 'Status',
key: 'status',
width: 164,
},
{
title: 'Subscription',
key: 'subscription',
width: 90,
},
],
};
return(
<div><DataTable
tableSettings={tableSettings}
apiLocation={this.props.services}
/>
</div>
)}
This will resolve your issue.

Related

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: "",
});
});

Toggle Dark Mode with React, Next JS & Local Storage using MUI V5 Latest Version

Currently, I am developing a Web app built with NEXT JS and MUI 5 latest version alongside using GraphQL.
I am stacked with this point:
I do want to persistent the changing dark mode inside the LocalStorage alongside using this implementation of MUI guidelines by "https://mui.com/customization/dark-mode/#toggling-color-mode".
Is there anyone who can guide me through if I toggle the switch then the Dark or Light mode gonna set in the localStorage? I need all your suggestions.
I am Using with Context API:
import { createContext, useMemo, useState } from 'react'
import { createTheme, ThemeProvider } from '#mui/material/styles'
// TODO: Export this one
export const ColorModeContext = createContext({ toggleColorMode: () => {} })
const ThemeContext = ({ children }) => {
const [mode, setMode] = useState('dark')
const colorMode = useMemo(
() => ({
toggleColorMode: () => {
setMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light'))
},
}),
[]
)
const theme = useMemo(
() =>
createTheme({
palette: {
mode,
primary: {
light: '#757ce8',
main: '#3f50b5',
dark: '#002884',
contrastText: '#fff',
},
secondary: {
light: '#ff7961',
main: '#f44336',
dark: '#ba000d',
contrastText: '#000',
},
},
}),
[mode]
)
return (
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={theme}>{children}</ThemeProvider>
</ColorModeContext.Provider>
)
}
export default ThemeContext
I implemented in my AppBar stuff like this:
// * ___main_appbar_function___
export default function MyAppBar(props) {
const theme = useTheme()
const colorMode = useContext(ColorModeContext)
return (
<NoSsr>
<CssBaseline />
<HideOnScroll {...props}>
<AppBar color='inherit'>
<Toolbar variant='dense' component='div'>
<Box sx={root}>
<MySideBar />
<Typography component='div' variant='h5' textAlign='center'>
PJK
</Typography>
<Box sx={right}>
{/* <AuthModal /> */}
<motion.div
whileTap={{ rotate: 360 }}
// whileHover={{ rotate: 360 }}
transition={{ type: 'spring', stiffness: 50 }}
>
<IconButton onClick={refreshPage}>
<RotateRightIcon />
</IconButton>
</motion.div>
<IconButton
sx={{ ml: 1 }}
onClick={colorMode.toggleColorMode}
color='inherit'
>
{theme.palette.mode === 'dark' ? (
<Brightness7Icon />
) : (
<Brightness4Icon />
)}
</IconButton>
</Box>
</Box>
</Toolbar>
</AppBar>
</HideOnScroll>
<Toolbar />
</NoSsr>
)
}
Try this
const MODE = "mode";
const [mode, setMode] = useState(() => {
// for the sake of solving this issues
// ("ReferenceError: localStorage is not defined")
if (typeof window !== 'undefined') {
localStorage.getItem(MODE) || 'dark'
}
});
const colorMode = useMemo(
() => ({
toggleColorMode: () => {
setMode(prevMode => {
const nextMode = prevMode === "light" ? "dark" : "light";
localStorage.setItem(MODE, nextMode);
return nextMode;
});
}
}),
[]
);
This seem to work for me, it detects the system preference and has a option to toggle between dark and light mode, might not be the best way, it seems to work for me.
App.js
import React from 'react';
import {
ThemeProvider,
createTheme,
responsiveFontSizes,
} from '#mui/material/styles';
import { deepmerge } from '#mui/utils';
import useMediaQuery from '#mui/material/useMediaQuery';
import { getDesignTokens, getThemedComponents } from 'theme/Theme';
import { ColorModeContext } from 'config/color-context';
export default function App() {
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const [mode, setMode] = React.useState();
React.useEffect(() => {
setMode(prefersDarkMode ? 'dark' : 'light');
}, [prefersDarkMode]);
const colorMode = React.useMemo(
() => ({
toggleColorMode: () => {
setMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light'));
},
}),
[]
);
let theme = React.useMemo(
() =>
createTheme(deepmerge(getDesignTokens(mode), getThemedComponents(mode))),
[mode]
);
theme = responsiveFontSizes(theme);
return (
<ColorModeContext.Provider value={colorMode}>
<ThemeProvider theme={theme}>
...
</ThemeProvider>
</ColorModeContext.Provider>
);
}
theme/Theme.js
import { amber, deepOrange, grey, blue, common } from '#mui/material/colors';
const palette = {
light: {
primary: {
main: '#34C0AC',
light: '#B1DED3',
dark: '#00765A',
},
},
};
export const getDesignTokens = (mode) => ({
palette: {
mode,
...(mode === 'light'
? {
primary: {
main: palette.light.primary.main,
light: palette.light.primary.light,
dark: palette.light.primary.dark,
},
divider: amber[200],
text: {
primary: grey[900],
secondary: grey[800],
},
}
: {
primary: deepOrange,
divider: deepOrange[700],
background: {
default: deepOrange[900],
paper: deepOrange[900],
},
text: {
primary: '#fff',
secondary: grey[500],
},
}),
},
typography: {
fontFamily: [
'Oswald',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
].join(','),
body1: {
fontFamily: 'Poppins, Arial, sans-serif',
},
},
});
export const getThemedComponents = (mode) => ({
components: {
...(mode === 'light'
? {
MuiAppBar: {
styleOverrides: {
colorPrimary: {
backgroundColor: grey[800],
},
},
},
MuiLink: {
variant: 'h3',
},
MuiButton: {
styleOverrides: {
root: {
borderRadius: 0,
color: common.white,
fontFamily:
"Oswald, Roboto, 'Helvetica Neue', Arial, sans-serif",
fontSize: 20,
borderWidth: 2,
'&:hover': {
borderWidth: 2,
},
},
},
variants: [
{
props: { variant: 'contained' },
style: {
fontFamily:
"Oswald, Roboto, 'Helvetica Neue', Arial, sans-serif",
},
},
{
props: { variant: 'outlined' },
style: {
color: palette.light.primary.main,
},
},
{
props: { variant: 'primary', color: 'primary' },
style: {
border: '4px dashed blue',
},
},
],
},
MuiList: {
styleOverrides: {
root: {},
},
},
MuiMenuItem: {
styleOverrides: {
root: {
color: common.white,
alignItems: 'stretch',
fontFamily:
"Oswald, Roboto, 'Helvetica Neue', Arial, sans-serif",
},
},
},
MuiAccordion: {
styleOverrides: {
root: {
color: common.white,
fontFamily:
"Oswald, Roboto, 'Helvetica Neue', Arial, sans-serif",
},
},
},
}
: {
MuiAppBar: {
styleOverrides: {
colorPrimary: {
backgroundColor: blue[800],
},
},
},
}),
},
});
config/color-context.js
import React from 'react';
export const ColorModeContext = React.createContext({
toggleColorMode: () => {
// This is intentional
},
});
ThemeToggler.js
import React from 'react';
import { IconButton, Box } from '#mui/material';
import { useTheme } from '#mui/material/styles';
import Brightness4Icon from '#mui/icons-material/Brightness4';
import Brightness7Icon from '#mui/icons-material/Brightness7';
import { ColorModeContext } from 'config/color-context';
export default function SubHeaderNavigation() {
const theme = useTheme();
const colorMode = React.useContext(ColorModeContext);
return (
<Box
sx={{
display: 'flex',
width: '100%',
alignItems: 'center',
justifyContent: 'center',
bgcolor: 'background.default',
color: 'text.primary',
borderRadius: 1,
p: 3,
}}
>
{theme.palette.mode} mode
<IconButton
sx={{ ml: 1 }}
onClick={colorMode.toggleColorMode}
color="inherit"
>
{theme.palette.mode === 'dark' ? (
<Brightness7Icon />
) : (
<Brightness4Icon />
)}
</IconButton>
</Box>
);
}
Try this
const Home = () => {
const [isDarkMode, setDarkMode] = React.useState(false);
React.useEffect(() => {
window.localStorage.getItem('theme') == 'true' ? setDarkMode(true) : setDarkMode(false)
}, [])
const toggleDarkMode = () => {
setDarkMode(!isDarkMode);
window.localStorage.setItem("theme", !isDarkMode);
console.log(window.localStorage.getItem('theme'))
};
return (
<div className={(isDarkMode ? 'dark' : '') + ' main'}>
</div>
)
}

Issue displaying table in VueJS using Tabulator

I am trying to set up a basic Tabulator table in Vue.JS and I see the table but the styling is broken.
I set up a new(basic) VueJS project and followed the instructions for Vue setup listed here: http://tabulator.info/docs/4.1/frameworks#vue
I added some sample data and the ran the app (npm run dev)
Here is my code:
Testpage.vue
<script>
var Tabulator = require('tabulator-tables')
export default {
name: 'Test',
data: function () {
return {
tabulator: null, // variable to hold your table
tableData: [
{name: 'Billy Bob', age: '12'},
{name: 'Mary May', age: '1'}
] // data for table to display
}
},
watch: {
// update table if data changes
tableData: {
handler: function (newData) {
this.tabulator.replaceData(newData)
},
deep: true
}
},
created: function () {
console.log('Test', this.$refs)
},
mounted () {
// instantiate Tabulator when element is mounted
this.tabulator = new Tabulator(this.$refs.table, {
data: this.tableData, // link data to table
columns: [
{title: 'Name', field: 'name', sorter: 'string', width: 200, editor: true},
{title: 'Age', field: 'age', sorter: 'number', align: 'right', formatter: 'progress'}
]
})
},
template: '<div ref="table"></div>'
}
</script>
App.vue:
<template>
<div id="app">
<img src="./assets/logo.png">
<router-view/>
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
Main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
Router(index.js)
import Vue from 'vue'
import Router from 'vue-router'
import Test from '#/components/TestPage'
import HelloWorld from '#/components/HelloWorld'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{ path: '/test', name: 'Test', component: Test }
]
})
I expect to see a styled table like the demo shows in the documentation.
A table with no styling appears on the page. (No borders, colors, etc)
you need to include the /dist/css/tabulator.css file from the Tabulator directory in your project with the rest of your CSS to bring in the table styling.
How you do that will depend on the evironment you are developing in
I tried to set up the described minimal Vue.JS Project on my own but encountered the following message in the console
> [Vue warn]: You are using the runtime-only build of Vue where the
> template compiler is not available. Either pre-compile the templates
> into render functions, or use the compiler-included build.
To avoid this message, it was necessary to modify the Testpage.vue. In my case it worked to move the key 'template' with its value from script section to its own 'template' section.
<template>
<div ref="table"></div>
</template>
<script>
const Tabulator = require('tabulator-tables');
export default {
name: 'Test',
data() {
return {
tabulator: null, // variable to hold your table
tableData: [
{ name: 'Billy Bob', age: '12' },
{ name: 'Mary May', age: '1' },
], // data for table to display
};
},
watch: {
// update table if data changes
tableData: {
handler(newData) {
this.tabulator.replaceData(newData);
},
deep: true,
},
},
created() {
// console.log('Test', this.$refs);
},
mounted() {
// instantiate Tabulator when element is mounted
this.tabulator = new Tabulator(this.$refs.table, {
data: this.tableData, // link data to table
columns: [
{
title: 'Name', field: 'name', sorter: 'string', width: 200, editor: true,
},
{
title: 'Age', field: 'age', sorter: 'number', align: 'right', formatter: 'progress',
},
],
});
},
};
</script>

SideMenu layout example react-native-navigation v2

I need an example with sideMenu react-native-navigation v2. Ideally, I want to navigate from side menu component to other screens (e.g stack with bottom tabs, accounts screen, FAQs screen)
currently this is my layout
Navigation.setRoot({
root: {
sideMenu: {
left: {
component: {
name: 'screen.SideMenu',
}
},
center: {
bottomTabs: {
id: 'tabs',
options: {
topbar: {
visible: true,
}
},
children: [
{
stack: {
id: 'tab1',
children: [
{
component: {
name: 'screen.Home',
options: {
topbar: {
visible: true
},
bottomTab: {
fontSize: 12,
text: 'Home',
icon: homeIcon,
textColor: theme.$tabColor,
selectedTextColor: '#000',
selectedIconColor: '#000',
}
}
},
},
]
}
},
{
stack: {
id: 'tab2',
children: [
{
component: {
name: 'screen.Events',
options: {
bottomTab: {
text: 'Events',
fontSize: 12,
icon: eventsIcon,
textColor: theme.$tabColor,
selectedTextColor: '#000',
selectedIconColor: '#000',
}
}
},
},
]
}
},
],
},
}
}
}
});
In my Side Menu component I am calling this function.
goToAccountsScreen = () => {
console.log(this.props.componentId)
Navigation.push(this.props.componentId, {
component: {
name: 'screen.Accounts',
}
})
}
how do I add the Accounts screen to my layout

get svg code in highchart directive with angular js

in normal highchart i get svg code with code like this
var chart = $('#container').highcharts()
svg = chart.getSVG();
So, how can i get svg code with this highchart directive in angular js???
i try like normal code but i didn't get svg code.
i use this directive for my highchart
https://github.com/rootux/angular-highcharts-directive
and this my code in controller.js
$scope.chartLogisticGIGR = {
options: {
tooltip: {
shared: true
}
},
xAxis: { // Primary xAxis
categories: $scope.nameMonths,
title: {
text: 'Month'
},
labels: {
enabled: true
},
min:0
},
yAxis: [{ // Primary yAxis
title: {
text: 'GI / GR in IDR'
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value / 1000000,'0') + ' mil';
}
}
}, { // Secondary yAxis
title: {
text: 'Balance'
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value / 1000000,'0') + ' mil';
}
},
}],
series: [{
name: 'AGP - Goods Receipt',
type: 'column',
stacking: 'normal',
stack: '1',
data: $scope.dataLogisticGIGR_AGP_GR,
color: $rootScope.getColor('AGP Ext'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AGP - Goods Issue',
type: 'column',
stacking: 'normal',
stack: '1',
data: $scope.dataLogisticGIGR_AGP_GI,
color: $rootScope.getColor('AGP Int'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AGP - Balance',
type: 'spline',
data: $scope.dataLogisticGIGR_AGP_Balance,
color: $rootScope.getColor('AI 2'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AI - Goods Receipt',
type: 'column',
stacking: 'normal',
stack: '3',
data: $scope.dataLogisticGIGR_AI_GR,
color: $rootScope.getColor('AI'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AI - Goods Issue',
type: 'column',
stacking: 'normal',
stack: '3',
data: $scope.dataLogisticGIGR_AI_GI,
color: $rootScope.getColor('AP 2'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
},{
name: 'AI - Balance',
type: 'spline',
data: $scope.dataLogisticGIGR_AI_Balance,
color: $rootScope.getColor('AP'),
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}: {point.y:,.0f}</span><br/>'
}
}],
title: {
text: ''
},
loading: false
};
in this is my code in directive highchart
'use strict';
angular.module('chartsExample.directives',[])
.directive('chart', function () {
return {
restrict: 'E',
template: '<div></div>',
scope: {
chartData: "=value"
},
transclude:true,
replace: true,
link: function (scope, element, attrs) {
var chartsDefaults = {
chart: {
renderTo: element[0],
type: attrs.type || null,
height: attrs.height || null,
width: attrs.width || null
}
};
//Update when charts data changes
scope.$watch(function() { return scope.chartData; }, function(value) {
if(!value) return;
// We need deep copy in order to NOT override original chart object.
// This allows us to override chart data member and still the keep
// our original renderTo will be the same
var newSettings = {};
angular.extend(newSettings, chartsDefaults, scope.chartData);
var chart = new Highcharts.Chart(newSettings);
});
}
};
});
Thank's....

Resources