No result using makeStyles Material UI in react 18 - javascript

Hi Im exploring ReactJs and Material UI and Im following outdated tutorials. I having a problem with this material UI makestyles how do I use this? This is the format that Im using and there are no results. As you see I update the material UI import too
styles.js
import { makeStyles } from "#mui/material/styles";
export default makeStyles(() => ({
appBar: {
borderRadius: 15,
margin: "30px 0",
display: "flex",
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
},
heading: {
color: "rgba(0,183,255, 1)",
},
image: {
marginLeft: "15px",
},
}));
App.js
import useStyles from "./styles";
const App = () => {
const classes = useStyles();
return (
<Container maxwidth="lg">
<AppBar className={classes.appBar} position="static" color="inherit">
<Typography className={classes.heading} variant="h2" align="center">
Memories
</Typography>
<img
className={classes.image}
src={memories}
alt="memories"
height="60"
Well I can use style inside a file but I want to make a style in another file like style.js to make it more cleaner.
const App = () => {
// const classes = useStyles();
return (
<Container maxwidth="lg">
<AppBar
style={{
borderRadius: 15,
margin: "30px 0",
display: "flex",
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
}}
position="static"
color="inherit"
>
<Typography variant="h2" align="center">
Memories
</Typography>
<img src={memories} alt="memories" height="60" />
</AppBar>

styles.js
import { makeStyles } from "#mui/material/styles";
export const useStyles = makeStyles(() => ({
appBar: {
borderRadius: 15,
margin: "30px 0",
display: "flex",
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
},
heading: {
color: "rgba(0,183,255, 1)",
},
image: {
marginLeft: "15px",
},
}));

This will definitely solve your problem!
styles.js
❌import { makeStyles } from "#mui/material/styles"; // <--- delete this ❌
import { styled } from "#mui/system"; // <--- Add this ✅
❌export default makeStyles(() => ({ // <--- delete this ❌
export default styled(()=>({ // <--- Add this ✅
appBar: {
borderRadius: 15,
margin: "30px 0",
display: "flex",
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
},
heading: {
color: "rgba(0,183,255, 1)",
},
image: {
marginLeft: "15px",
},
}));
Reason:
The #mui/styles package is not compatible with React 18, as shown in the documentation - Documentation.
You should migrate to either #mui/system and use styled(), sx, etc,
Documentation for sx props > SX Props Docs MUI
sx props -> property is used like inline styling.
for example :
<Box
sx={{
bgcolor: 'background.paper',
boxShadow: 1,
borderRadius: 2,
p: 2,
minWidth: 300,
}}
>
</Box>
or *migrate* to **tss-react**
which has an API which is closer to #mui/styles . I hope this explanation helps other who may come to this issue.

import {styled } from "#mui/material";
const useStyles = styled((theme) => ({
toolbarMargin: {
...theme.mixins.toolbar
}
}));
const Header = () => {
const classes = useStyles();
return (
<Fragment>
<AppBar position="fixed">
<Toolbar>
<h1>Brand Name</h1>
<Button variant="contained" color="error" sx={{ marginLeft: "auto" }}>
Connect Wallet
</Button>
</Toolbar>
</AppBar>
<div className={classes.toolbar} />
</Fragment>
);
};

#mui/styles no longer works in React 18.
Try this:
import { styled } from "#mui/system";
export default styled(()=>({
appBar: {
borderRadius: 15,
margin: "30px 0",
display: "flex",
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
},
heading: {
color: "rgba(0,183,255, 1)",
},
image: {
marginLeft: "15px",
},
}));

You can import makeStyles from tss-react instead of from MUI
According to: https://github.com/mui/material-ui/issues/32881#issuecomment-1135051663

Related

How can I add space Inbetween text as in react native gap css is not working

Here I want space between test1 and test2.
import React from "react";
import { StyleSheet, View } from "react-native";
function App() {
const data = ["test1", "test2", "test3"];
return (
<View style={styles.app}>
{data.map((text) => (
<span style={styles.span}>{text}</span>
))}
</View>
);
}
const styles = StyleSheet.create({
app: {
marginTop: 30,
position: "absolute",
backgroundColor: "yellow",
left: "8px",
widht: "auto",
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between"
},
span: {
gap: 20
}
});
export default App;
But currently it look like this
https://codesandbox.io/s/blissful-sea-tlbjso?file=/src/App.js
How can I achive this through css ?
Updated------------------------------------------------------
if I add marginRight in span then it will add extra space at the end of the text.
You need to add the gap property alongside display: flex inside the class app.
import React from "react";
import { StyleSheet, View } from "react-native";
function App() {
const data = ["test1", "test2", "test3"];
return (
<View style={styles.app}>
{data.map((text) => (
<span>{text}</span>
))}
</View>
);
}
const styles = StyleSheet.create({
app: {
marginTop: 30,
position: "absolute",
backgroundColor: "yellow",
left: "8px",
width: "auto",
flexDirection: "row",
display: "flex",
gap: 10,
alignItems: "center",
justifyContent: "space-between"
}
});
export default App;
https://codesandbox.io/s/upbeat-chebyshev-22kuqd?file=/src/App.js:0-573

Multiple Input Text handle in object and array in react native

This is my code ....
react native
Multiple Input Text handle in object and array in react native...
Is it possible to share your code? Share the entire component where you have these groups of 5 inputs. You can just copy and paste it inside your question body. That way I can help you better
App.js
import {
StyleSheet,
Pressable,
View,
} from 'react-native';
import {
AntDesign,
FontAwesome
} from '#expo/vector-icons';
import { useState } from 'react';
import AddStudentProfile from './Pages/AddStudentProfile';
import StudentList from './Pages/StudentList';
export default function App() {
const [iconColor, setIconColor] = useState(['#ab09bf', '#A9A9A9']);
const [multiValues, setMultiValues] = useState([]);
const [screen, setScreen] = useState(<StudentList stuList={multiValues} />);
function changeIconColor(pressCheck) {
if (pressCheck) {
setIconColor([
'#ab09bf',
'#A9A9A9'
]
);
}
else {
setIconColor([
'#A9A9A9',
'#ab09bf'
]
);
}
}
// const [iconChangableColor, setIconChangableColor] = useState('#A9A9A9');
function changeScreen(scr) {
setScreen(
// < AddStudentProfile />
scr
);
// setIconChangableColor('#ab09bf');
// console.log(multiValues)
changeIconColor(true)
}
function appendData(inp, onsrcChange) {
setScreen(
// < AddStudentProfile />
onsrcChange
);
setMultiValues([
...multiValues,
inp]);
console.log(multiValues)
}
return (
< View style={styles.container} >
<View style={{ flex: 9 }}>{screen}
</View>
<View >
<View style={styles.bottomIconContainer}>
<Pressable onPress={() => [changeScreen(<StudentList />), changeIconColor(true)]}
android_ripple={{ color: 'black' }}>
<View style={styles.bottomIconInnerContainer}>
<FontAwesome
name="list-ul"
size={35}
color={iconColor[0]} />
</View></Pressable>
<Pressable onPress={() => [changeScreen(<AddStudentProfile onAppendData={appendData} returnToProfile={changeScreen} />), changeIconColor(false)]}
android_ripple={{ color: 'black' }}>
<View style={styles.bottomIconInnerContainer}>
<AntDesign name="adduser"
size={35}
color={iconColor[1]}
/></View></Pressable></View>
</View>
</View >
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
bottomIconContainer: {
flexDirection: 'row',
justifyContent: 'space-around',
alignItems: 'center',
},
bottomIconInnerContainer: {
marginVertical: 20,
marginHorizontal: 80
}
});
AddStudentProfile.js
import {
Text,
TextInput,
ImageBackground,
View,
Button,
ScrollView,
StatusBar,
StyleSheet
} from "react-native";
import { useState } from "react";
import { AntDesign } from '#expo/vector-icons';
import PrimaryButton from "../Componenets/PrimaryButton";
import ColorCode from "../Componenets/ColorCode.js";
export default function AddStudentProfile({ returnToProfile, onAppendData }) {
const [values, setValues] = useState({});
function inputHandler(name, value) {
setValues({
...values,
[name]: value
})
}
function inpValues(srcChange) {
onAppendData(values, srcChange)
console.log(values)
}
return (
<ScrollView>
<View style={styles.screenContainer}>
<View>
<Text style={styles.textContainer}>
Add Student Profile
</Text>
</View>
<View style={styles.iconOutterContainer}>
<View style={styles.iconContainer}>
<AntDesign
name="user"
size={80}
color='white'
/>
</View>
</View>
<View style={{ alignItems: 'center' }}>
<TextInput
style={styles.inputTextContainer}
placeholder="name"
placeholderTextColor={ColorCode.placeHolder}
onChangeText={(val) => inputHandler('sname', val)}
/>
<TextInput
style={styles.inputTextContainer}
placeholder="roll no"
placeholderTextColor={ColorCode.placeHolder}
onChangeText={(val) => inputHandler('rno', val)}
/>
<TextInput
style={styles.inputTextContainer}
placeholder="department"
placeholderTextColor={ColorCode.placeHolder}
onChangeText={(val) => inputHandler('dep', val)}
/>
<TextInput
style={styles.inputTextContainer}
placeholder="e-mail"
placeholderTextColor={ColorCode.placeHolder}
onChangeText={(val) => inputHandler('mail', val)}
/>
<TextInput
style={styles.inputTextContainer}
placeholder="Phone no"
placeholderTextColor={ColorCode.placeHolder}
onChangeText={(val) => inputHandler('phno', val)}
/>
</View>
<PrimaryButton
onreturnToProfile={returnToProfile}
inputValues={inpValues}
changeColor='#8a0896'
>Save</PrimaryButton>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
iconContainer: {
height: 100,
width: 100,
borderRadius: 100,
backgroundColor: '#ab09bf',
alignItems: 'center',
justifyContent: 'center'
},
textContainer: {
marginVertical: 10,
textAlign: 'center',
fontSize: 20,
},
screenContainer: {
marginTop: StatusBar.currentHeight,
flex: 1,
padding: 20
},
iconOutterContainer: {
alignItems: 'center'
},
inputOutterContainer: {
padding: 10,
marginHorizontal: 5
},
inputTextContainer: {
padding: 10,
backgroundColor: '#fff',
marginVertical: 10,
width: '95%',
fontSize: 19,
elevation: 5,
borderRadius: 6,
shadowColor: '#ab09bf',
color: '#ab09bf'
},
buttonOutterContainer: {
width: '30%',
marginHorizontal: 10,
fontSize: 20
},
buttonInnerContainer: { fontSize: 23 }
});
PrimaryButton.js
import {
View,
Text,
Pressable,
StyleSheet
} from 'react-native';
import StudentList from '../Pages/StudentList';
export default function PrimaryButton({ children, inputValues, onreturnToProfile }) {
function pressHandler() {
//onreturnToProfile();
inputValues(<StudentList />)
}
return (
< View style={{ alignItems: 'center', marginTop: 15 }
}>
<View
style={styles.textOutterContainer}
>
<Pressable
onPress={pressHandler}
android_ripple={{ color: 'white' }}
>
<Text style={styles.textContainer}>{children}</Text>
</Pressable>
</View>
</View >
);
}
const styles = StyleSheet.create({
textContainer: {
fontSize: 23,
color: 'white',
textAlign: 'center'
},
textOutterContainer: {
backgroundColor: '#8a0896',
borderRadius: 22,
width: '20%',
height: 40,
alignItems: 'center',
justifyContent: 'center'
}
})
I have gone through your code and it seems to be right even though a bit complicated. What is the issue you are facing?
You are adding a set of student info(5 fields) on a button press to a parent component state. You are appending it to an empty array. Ideally, you should get something like the below. What seems to be the problem? Please explain.
multiValues = [
{
'sname': 'some sname',
'rno': 'some rno',
'dep': 'some dep',
'mail': 'some mail',
'phno': 'some phno'
},
{
'sname': 'some sname',
'rno': 'some rno',
'dep': 'some dep',
'mail': 'some mail',
'phno': 'some phno'
},
{
'sname': 'some sname',
'rno': 'some rno',
'dep': 'some dep',
'mail': 'some mail',
'phno': 'some phno'
},
{
'sname': 'some sname',
'rno': 'some rno',
'dep': 'some dep',
'mail': 'some mail',
'phno': 'some phno'
},
]
Will update this answer depending on your response so that it might be of help to someone else.

React Native Elevation shadow does not work properly

I am new to React Native, I tried to create a component for my radio button but I encountered some issue with the Style when I added the elevation, and it is adding the shadow inside the View instead of outside of the View
Here is my code
import {Text, View, StyleSheet} from 'react-native';
import {RadioButton} from 'react-native-paper';
import {
ScrollView,
TextInput,
TouchableOpacity,
} from "react-native-gesture-handler";
function Chosen({values, onChange, defaultIndex, selectedIndexAtt, renderComponent}){
const [index, setIndex] = useState(defaultIndex ? defaultIndex : 0);
const getRadioStatus = (itemIndex) => {
return index == itemIndex ? 'checked' : 'unchecked';
}
const handleRadioPress = (itemIndex) => {
setIndex(itemIndex);
onChange(itemIndex);
}
return(
<ScrollView style={styles.container}>
<View style={styles.containerRow}>
{values.map((item, index)=> {
return (<View style={styles.itemContainer}>
<View style={styles.item}>
{renderComponent(item)}
<View style={styles.radioButton}>
<RadioButton value={item[selectedIndexAtt ? selectedIndexAtt : index]}
status={getRadioStatus(item[selectedIndexAtt ? selectedIndexAtt : index])}
onPress={() => {
handleRadioPress(item[selectedIndexAtt ? selectedIndexAtt : index])
}}/>
</View>
</View>
</View>)
})}
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
container:{
flexDirection: 'column',
flex: 1
},
containerRow:{
flexDirection: 'row',
flexWrap: 'wrap',
},
itemContainer: {
width: "50%",
padding: 1
},
item: {
flexDirection: 'row',
margin: 10,
borderWidth: 1,
borderColor: 'rgba(105,105,105,0.6)',
borderRadius: 15,
elevation: 0.1
},
radioButton: {
justifyContent: 'center',
flex: 1,
alignItems: 'flex-end'
}
});
export default Chosen;
and here is how I call it from the parent
<Chosen values={dummyData} defaultIndex={dummyData[0].id} selectedIndexAtt='id' renderComponent={(item) => {
return (
<View>
<Text>{item.name}</Text>
</View>
)
}} onChange={onChange}></Chosen>
and the result is this:
elevation shadow issue
Can someone please help me with this?
You have to provide this for a shadow in react native. Change the values according to your need.
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 10,
},
shadowOpacity: 0.5,
shadowRadius: 10,
elevation: 20,

Undefined is not a function (near '... map ...')

When I tap in the Pressable element in the JSX I get the error : Undefined is not a function (near '... wines.map ...'). The log says it's coming from the wines.map loop in the JSX. I'm unsure on what could be wrong with how I'm trying to change the data in the toggle function or how I set the default useState array object. The code is supposed to toggle between two different kind of images for each button independently.
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* #format
* #flow strict-local
*/
import 'react-native-gesture-handler';
import React, {useState} from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
ImageBackground,
Image,
TextInput,
Button,
TouchableNativeFeedback,
TouchableWithoutFeedback,
TouchableOpacity,
TouchableHighlight,
FlatList,
Pressable,
RecyclerViewBackedScrollViewComponent
} from 'react-native';
import { Immersive } from 'react-native-immersive';
const fullWine = require('../images/selected-wine.png');
const emptyWine = require('../images/empty-wine-icon.png');
const WineList = () => {
Immersive.on()
Immersive.setImmersive(true)
const [wines, setWines] = useState([
{
name: "2018 Prezzo",
info: "What dsbetter way to spend a lazy afternoon than sipping away on this wine.",
imageUrl: emptyWine
},
{
name: "2018 Coqueta",
info: "A litstle flirty wine.",
imageUrl: emptyWine
}
])
function toggle(pressedWine){
let oldWines = [...wines]
let newWines = oldWines.map((wine) => {
if(wine === pressedWine){
if(wine.imageUrl == emptyWine){
wine.imageUrl = fullWine;
} else {
wine.imageUrl = emptyWine;
}
}
return wine;
});
setWines({newWines});
// setWines({newWines});
}
return (
<View style={{flex:1}}>
<ScrollView style={styles.scrollView}>
<View style={styles.headerMessage}>
<Text style={styles.headerMessageText}>Select your wines for tasting</Text>
</View>
<View style={[styles.wineListWrapper]}>
{ wines.map((wine, index) => {
return(
<View key={index} style={[styles.item]}>
<Image source={require('../images/Peresozo2018.png')} style={[styles.bottle]} />
<View style={[styles.infoWrapper]}>
<Text style={[styles.itemTitle]}>{wine.name}</Text>
<Text style={[styles.itemInfo]}>
{wine.info}
</Text>
</View>
<Pressable onPress={ (wine) => toggle(wine) } style={[styles.wineIcon]}>
<Image source={wine.imageUrl} />
</Pressable>
</View>
)
})}
</View>
</ScrollView>
<TouchableOpacity onPress={() => alert('yo') } style={[styles.footerButton]}>
<Text style={[styles.footerText]}>Start Tasting</Text>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
footerButton:{
flex:1,
justifyContent: 'flex-end',
alignContent:'center',
alignItems:'center',
backgroundColor:'white',
paddingTop:90
},
footerText:{
fontFamily: 'Charm-Regular',
fontSize:40,
color:'#624124'
},
item:{
flex:1,
flexDirection: 'row',
justifyContent: 'space-between',
padding: 10
},
infoWrapper:{
flex:0.7,
flexWrap: 'wrap',
flexDirection: 'row',
padding:10,
alignSelf:'flex-start',
justifyContent: 'space-between',
marginTop: -30,
marginLeft:1
},
itemTitle:{
color:'white',
fontFamily: 'Charm-Regular',
fontSize: 40,
},
itemInfo:{
color:'white',
fontSize: 20,
},
wineIcon:{
padding:5,
flex:0.15
},
wineListWrapper:{
marginLeft: 10,
marginTop: 40
},
bottle:{
marginLeft: 2,
width: 80,
height: 250,
resizeMode: 'contain',
},
scrollView:{
backgroundColor: '#4B4239',
},
headerMessage:{
backgroundColor: 'white',
flex: 1,
alignItems: 'center',
alignContent: 'center',
justifyContent: 'center',
flexDirection: 'column',
alignSelf: 'center',
width:400,
borderRadius: 4,
padding: 0,
marginTop: 10
},
headerMessageText:{
color: '#4B4239',
textAlign: 'center',
fontSize: 30,
fontFamily: 'Charm-Regular',
lineHeight: 50
}
})
export default WineList
The issue is that you're setting an object into the wines state when updating it:
setWines({ newWines });
Since the value of the state is an array, you probably meant:
setWines(newWines);
Additionally, the parameter passed to the onPress callback is not the wine object, but a PressEvent. As a result, you're shadowing the wine variable from the .map() with the event object from the callback's parameter.
You probably meant to pass the wine from the loop to toggle instead, so just remove the (wine) => parameter.
<Pressable onPress={() => toggle(wine)} style={[styles.wineIcon]}>
<Image source={wine.imageUrl} />
</Pressable>

react-native-draggable-flatlist not working inside ScrollView

I am struggling for last couple of months to achieve a requirement where I'm having a draggable flatlist and a flatlist in a single scrollview and I should able to scroll the whole content.
The draggable flatlist should have autoscroll as well, that means when the list is too long and I'm trying to drag it out of the viewport, the list should scroll automatically unless I drop it.
I know the requirement is pretty much tricky but I am not getting any clue to make it work completely.
I am using the below code and I am using 'react-native-draggable-flatlist'(https://github.com/computerjazz/react-native-draggable-flatlist) for this purpose.
Code:
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
TouchableOpacity
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import DraggableFlatList from 'react-native-draggable-flatlist'
import { Component } from 'react'
const exampleData = [...Array(20)].map((d, index) => ({
key: `item-${index}`, // For example only -- don't use index as your key!
label: index,
backgroundColor: `rgb(${Math.floor(Math.random() * 255)}, ${index *
5}, ${132})`
}));
class App extends Component {
state = {
data: exampleData,
scrollEnabled: true
};
onEnableScroll = (value: boolean) => {
this.setState({
enableScrollViewScroll: value,
});
};
renderItem = ({ item, index, drag, isActive }) => {
return (
<TouchableOpacity
style={{
height: 100,
backgroundColor: isActive ? "blue" : item.backgroundColor,
alignItems: "center",
justifyContent: "center"
}}
onLongPress={drag}
>
<Text
style={{
fontWeight: "bold",
color: "white",
fontSize: 32
}}
>
{item.label}
</Text>
</TouchableOpacity>
);
};
render() {
return (
<ScrollView
style={{ backgroundColor: '#000', flex: 1 }}
contentContainerStyle={{ paddingTop: 800, paddingBottom: 100 }}
scrollEnabled={this.state.scrollEnabled}
>
<DraggableFlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
onMoveBegin={() => this.setState({ scrollEnabled: false })}
onMoveEnd={({ data }) => {
this.setState({ scrollEnabled: true, data });
}}
/>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
/>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
engine: {
position: 'absolute',
right: 0,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: Colors.dark,
},
highlight: {
fontWeight: '700',
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
});
export default App;
You should use ListFooterComponent and ListHeaderComponent method to render items.
Please change your render method like below code.
render() {
return (
<View
style={{ backgroundColor: '#000', flex: 1 }}
>
<DraggableFlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
onMoveBegin={() => this.setState({ scrollEnabled: false })}
onMoveEnd={({ data }) => {
this.setState({ scrollEnabled: true, data });
}}
ListFooterComponent={() => {
return <View>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => `draggable-item-${item.key}`}
/>
</View>
}}
/>
</View>
);
}
In my case, I have another ScrollView composition.
My solution was found in this repository:
React Native Draggable FlatList
I replaced:
ScrollView -> NestableScrollContainer
DraggableFlatList -> NestableDraggableFlatList
Initially there was one DraggableFlatList but in this case I was able to scroll via the DraggableFlatList

Categories

Resources