React material-table - center table title - javascript

I am using material-table with my react project.
How I can center table title ?
Here is codesandbox example:
https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js
I want to make title "Average Expense ratio" to be in the center:
I tried adding style prop to the MaterialTable with textAlign:"center" but it does not work. Is it even possible to do it?

You can override Toolbar component and provide custom title react component if required.
import "./styles.css";
import MaterialTable, { MTableToolbar } from "material-table";
import Typography from "#material-ui/core/Typography";
const MyNewTitle = ({ text, variant }) => (
<Typography
variant={variant}
style={{
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis"
}}
>
{text}
</Typography>
);
export default function App() {
const softRed = "#CC6666";
//GREENS
const forestgreen = "#556B2F";
const limegreen = "#228B22";
const lightgreen = "#3CB371";
//ORANGES
const softOrange = "#ffd27f";
return (
<div className="App">
<MaterialTable
style={{}}
title={<MyNewTitle variant="h6" text="Average Expense Ratio" />}
components={{
Toolbar: (props) => (
<div
style={{
alignItems: "center",
justifyContent: "center",
display: "flex"
}}
>
<MTableToolbar {...props} />
</div>
)
}}
columns={[
{
title: "0.19 and below",
field: "first",
headerStyle: {
backgroundColor: forestgreen
}
},
{
title: "0.20 to 0.48",
field: "first",
headerStyle: {
backgroundColor: limegreen
}
},
{
title: "0.49 to 0.77",
field: "first",
headerStyle: {
backgroundColor: lightgreen
}
},
{
title: "0.78 to 1.06",
field: "first",
headerStyle: {
backgroundColor: softOrange
}
},
{
title: "1.07 and above",
field: "first",
headerStyle: {
backgroundColor: softRed
}
}
]}
data={[]}
options={{
headerStyle: {
color: "#FFF",
textAlign: "center",
whiteSpace: "nowrap",
fontSize: 10
},
paging: false,
search: false,
sorting: false,
showEmptyDataSourceMessage: false
}}
/>
</div>
);
}

Related

No result using makeStyles Material UI in react 18

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

change select element color to another when open

New to Material ui, i have this select element, i want to change the color of that input in the image to same as that 'None' section when select is clicked, so when user is able to see 'None' section then that input above it should have same background color as 'None' section and then when drop down is closed that input should change to gray
https://codesandbox.io/s/material-demo-forked-6hs9mm?file=/demo.js
code:
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import InputLabel from '#material-ui/core/InputLabel';
import MenuItem from '#material-ui/core/MenuItem';
import FormControl from '#material-ui/core/FormControl';
import Select from '#material-ui/core/Select';
import Button from '#material-ui/core/Button';
const useStyles = makeStyles((theme) => ({
button: {
display: 'block',
marginTop: theme.spacing(2),
},
formControl: {
margin: theme.spacing(1),
minWidth: 120,
},
select: {
borderBottom: 'opx',
'& ul': {
paddingTop: '0px',
paddingBottom: '0px',
},
'& ul:hover': {
backgroundColor: '#1E2328',
},
'& .Mui-selected': {
backgroundColor: '#1E2328',
color: '#E9ECEC',
fontWeight: '400, regular',
},
'& .Mui-selected:hover': {
backgroundColor: '#1E2328',
},
},
menuItemm: {
display: 'flex',
width: '225px',
height: '56px',
justifyContent: 'space-between',
// border: '1px solid gray',
backgroundColor: '#0B0B0B',
color: 'white',
},
placeholder: {
color: '#E9ECEC',
},
}));
export default function ControlledOpenSelect() {
const classes = useStyles();
const [age, setAge] = React.useState('');
const [open, setOpen] = React.useState(false);
const handleChange = (event) => {
setAge(event.target.value);
};
const handleClose = () => {
setOpen(false);
};
const handleOpen = () => {
setOpen(true);
};
return (
<div>
<FormControl className={classes.formControl}>
<InputLabel style={{backgroundColor:"gray",color:"white"}} id="demo-controlled-open-select-label">Age</InputLabel>
<Select
labelId="demo-controlled-open-select-label"
id="demo-controlled-open-select"
style={{backgroundColor:"gray",color:"white"}}
open={open}
MenuProps={{
classes: { paper: classes.select },
anchorOrigin: {
vertical: 'bottom',
horizontal: 'left',
},
transformOrigin: {
vertical: 'top',
horizontal: 'left',
},
getContentAnchorEl: null,
}}
onClose={handleClose}
onOpen={handleOpen}
value={age}
onChange={handleChange}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem className={classes.menuItemm}
value={10}>Ten</MenuItem>
<MenuItem className={classes.menuItemm}
value={20}>Twenty</MenuItem>
<MenuItem className={classes.menuItemm}
value={30}>Thirty</MenuItem>
</Select>
</FormControl>
</div>
);
}
these two should have same color when drop down is open:
and then when drop down is closed that input should change to gray color (backgroundColor).
i tried using usestate but then it changes color after dropdown is closed and not when opened:
https://codesandbox.io/s/material-demo-forked-2k0sow?file=/demo.js
English is not my mother language so could be mistakes
You should change this part
<Select labelId="demo-controlled-open-select-label"
id="demo-controlled-open-select"
style={{
backgroundColor: open ? "#1E2328" : "gray",
color: "white"
}}
Here is the codesandbox link https://codesandbox.io/s/material-demo-forked-exjez3?file=/demo.js
import React from "react";
import { makeStyles } from "#material-ui/core/styles";
import InputLabel from "#material-ui/core/InputLabel";
import MenuItem from "#material-ui/core/MenuItem";
import FormControl from "#material-ui/core/FormControl";
import Select from "#material-ui/core/Select";
import Button from "#material-ui/core/Button";
const useStyles = makeStyles((theme) => ({
button: {
display: "block",
marginTop: theme.spacing(2)
},
formControl: {
margin: theme.spacing(1),
minWidth: 120
},
select: {
borderBottom: "opx",
"& ul": {
paddingTop: "0px",
paddingBottom: "0px"
},
"& ul:hover": {
backgroundColor: "#1E2328"
},
"& .Mui-selected": {
backgroundColor: "#1E2328",
color: "#E9ECEC",
fontWeight: "400, regular"
},
"& .Mui-selected:hover": {
backgroundColor: "#1E2328"
}
},
menuItemm: {
display: "flex",
width: "225px",
height: "56px",
justifyContent: "space-between",
// border: '1px solid gray',
backgroundColor: "#0B0B0B",
color: "white"
},
placeholder: {
color: "#E9ECEC"
}
}));
export default function ControlledOpenSelect() {
const classes = useStyles();
const [age, setAge] = React.useState("");
const [open, setOpen] = React.useState(false);
const handleChange = (event) => {
setAge(event.target.value);
};
const handleClose = () => {
setOpen(false);
};
const handleOpen = () => {
setOpen(true);
};
return (
<div>
<FormControl className={classes.formControl}>
<InputLabel
style={{ backgroundColor: "gray", color: "white" }}
id="demo-controlled-open-select-label"
>
Age
</InputLabel>
<Select
labelId="demo-controlled-open-select-label"
id="demo-controlled-open-select"
style={{
backgroundColor: open ? "#1E2328" : "gray",
color: "white"
}}
open={open}
MenuProps={{
classes: { paper: classes.select },
anchorOrigin: {
vertical: "bottom",
horizontal: "left"
},
transformOrigin: {
vertical: "top",
horizontal: "left"
},
getContentAnchorEl: null
}}
onClose={handleClose}
onOpen={handleOpen}
value={age}
onChange={handleChange}
>
<MenuItem value="">
<em>None</em>
</MenuItem>
<MenuItem className={classes.menuItemm} value={10}>
Ten
</MenuItem>
<MenuItem className={classes.menuItemm} value={20}>
Twenty
</MenuItem>
<MenuItem className={classes.menuItemm} value={30}>
Thirty
</MenuItem>
</Select>
</FormControl>
</div>
);
}

How to create text border radius without wrap view in React Native?

In React-Native, how do I set borderRadius to Text-components?
I've tried using borderRadius in text stylesheet but it not work:
import { formatPhone, mapNameWithLocalContact } from '#chat/common/Utils/ChatUtils';
import ChatFunctions from '#chat/service/ChatFunctions';
import { Colors, Text } from '#momo-platform/component-kits';
import React from 'react';
import { StyleSheet, View, TextStyle } from 'react-native';
import { parseValue } from 'react-native-controlled-mentions';
import { MessageText } from 'react-native-gifted-chat';
// #ts-ignore
import ParsedText from 'react-native-parsed-text';
import { partTypes } from '../menstions';
const textStyle = {
fontSize: 16,
lineHeight: 20,
marginTop: 5,
marginBottom: 5,
marginLeft: 10,
marginRight: 10,
};
const styles = {
left: StyleSheet.create({
container: {},
text: {
color: 'black',
...textStyle,
},
link: {
color: 'black',
textDecorationLine: 'underline',
},
textMention: {
color: Colors.pink_05_b,
fontWeight: 'bold',
},
mentionMe: isMe =>
isMe
? {
color: Colors.white,
backgroundColor: Colors.pink_05_b,
}
: {},
}),
right: StyleSheet.create({
container: {},
text: {
color: 'white',
...textStyle,
},
link: {
color: 'white',
textDecorationLine: 'underline',
},
textMention: {
color: 'white',
fontWeight: 'bold',
},
mentionMe: () => ({}),
}),
};
export default class MessageTextCustom extends MessageText {
constructor() {
super(...arguments);
}
render() {
const linkStyle = [
styles[this.props.position].link,
this.props.linkStyle && this.props.linkStyle[this.props.position],
];
const { parts } = parseValue(this.props.currentMessage.text, partTypes);
return (
<View
style={[
styles[this.props.position].container,
this.props.containerStyle && this.props.containerStyle[this.props.position],
]}
>
<ParsedText
style={[
styles[this.props.position].text,
this.props.textStyle && this.props.textStyle[this.props.position],
this.props.customTextStyle,
]}
parse={[
...this.props.parsePatterns(linkStyle),
{ type: 'url', style: linkStyle, onPress: this.onUrlPress },
{ type: 'phone', style: linkStyle, onPress: this.onPhonePress },
{ type: 'email', style: linkStyle, onPress: this.onEmailPress },
]}
childrenProps={{ ...this.props.textProps }}
>
{this.props.isGroup ? (
<Text>
{parts.map(({ text, partType, data }, index) =>
partType ? (
<Text
key={`${index}-${data?.trigger ?? 'pattern'}`}
style={[
styles[this.props.position].textMention,
styles[this.props.position].mentionMe(
formatPhone(data.id) === ChatFunctions.phoneNumber
),
]}
onPress={() =>
this.props.onPressMenstion &&
this.props.onPressMenstion(data.id)
}
>
{`${data?.trigger}${mapNameWithLocalContact({
phone: data?.id,
name: data?.name,
})}`}
</Text>
) : (
<Text
key={index}
style={[
styles[this.props.position].text,
this.props.textStyle &&
this.props.textStyle[this.props.position],
this.props.customTextStyle,
]}
>
{text}
</Text>
)
)}
</Text>
) : (
this.props.currentMessage.text
)}
</ParsedText>
</View>
);
}
}
My expected style
I cannot use view to wrap this text because my text component is wrap by other text component
I've worked on it on snack you can check out this link and make sure you wrap those text with a View and use
flexDirection: 'row';
alignItems: 'center';
So to stop the View from filling the screen 100% add
alignSelf: 'start';
Checkout this link to see the code I've written for this
https://snack.expo.dev/#rajibola/spontaneous-beef-jerky
For TextStyle, borderTopRightRadius, borderTopLeftRadius, borderBottomRightRadius, borderBottomLeftRadius don't work. Only borderRadius works.
Maybe it's a bug!

Unable to update state in react native component using onChangeText

I have been trying to update the email and password value on submitting the form
so that I can pass them in my login API parameters. But I have tried almost everything, the value of this.state won't just update. Every time I try to print the value in console log e.g: cosole.log(this.state.email), it prints empty string i.e the default value set previously.
Here is my code below:
login.js
import React, { Component } from 'react';
import { ThemeProvider, Button } from 'react-native-elements';
import BliszFloatingLabel from './BliszFloatingLabel'
import {
StyleSheet,
Text,
View,
Image,
TextInput,
Animated,
ImageBackground,
Linking
} from 'react-native';
const domain = 'http://1xx.xxx.xx.xxx:8000';
class Login extends Component {
state = {
email: '',
password: '',
}
LoginAPI = (e,p) => {
console.log(e, "####")
}
handleEmail = (text) => {
this.setState({ email: text })
}
handlePassword = (text) => {
this.setState({ password: text })
}
goToSignUpScreen=() =>{
this.props.navigation.navigate('SignUpScreen');
};
goToForgotPasswordScreen=() =>{
this.props.navigation.navigate('ForgotPasswordScreen');
};
render() {
return (
<View style={styles.container} >
<ImageBackground source={require('../bgrndlogin.jpeg')} style={styles.image} >
<View style={styles.heading}>
<Image style={styles.logo} source={require('../loginlogo.png')} />
<Text style={styles.logoText}>Login</Text>
<Text style={styles.logodesc}>Please Login to continue --></Text>
</View>
<View style={styles.form_container}>
<BliszFloatingLabel
label="Email Id"
value={this.state.email}
onChangeText = {this.handleEmail}
onBlur={this.handleBluremail}
/>
<BliszFloatingLabel
label="Password"
value={this.state.password}
onChangeText = {this.handlePassword}
onBlur={this.handleBlurpwd}
secureTextEntry={true}
/>
<ThemeProvider theme={theme}>
<Button buttonStyle={{
opacity: 0.6,
backgroundColor: '#CC2C24',
borderColor: 'white',
borderWidth: 1,
width: 200,
height: 50,
marginTop: 30,
marginLeft: '20%',
alignItems: 'center',
justifyContent: "center"
}}
title="Login"
type="outline"
onPress = {
() => this.LoginAPI(this.state.email, this.state.password)
}
/>
</ThemeProvider>
<Text style={{
marginTop: 70,
color: '#CC2C24',
fontSize: 16,
fontWeight: "bold"
}}
onPress={
this.goToForgotPasswordScreen
}>
Forgot Password?
</Text>
<Text style={{
marginTop: 20,
color: '#CC2C24',
fontSize: 16,
fontWeight: "bold"
}}
onPress={
this.goToSignUpScreen
}>
Don't have an Account?
</Text>
</View>
</ImageBackground>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
logo: {
width: 115,
height: 50,
},
logoText: {
color: 'white',
fontSize: 36,
fontWeight: "bold"
},
logodesc: {
color: '#CC2C24',
fontSize: 18,
fontWeight: "bold"
},
heading: {
flex: 3,
marginLeft:20,
marginTop:30
},
form_container: {
flex: 7,
marginLeft:20,
marginTop:30,
marginRight: 20,
},
image: {
flex: 1,
resizeMode: "cover",
justifyContent: "center"
},
});
const theme = {
Button: {
titleStyle: {
color: 'white',
fontWeight: "bold",
fontSize: 18
},
},
};
export default Login;
I have created a common form as below which I inherit everywhere :
BliszFloatingLabel.js
import React, { Component } from 'react';
import {
Text,
View,
TextInput,
Animated,
} from 'react-native';
class BliszFloatingLabel extends Component {
state = {
entry: '',
isFocused: false,
};
UNSAFE_componentWillMount() {
this._animatedIsFocused = new Animated.Value(0);
}
handleInputChange = (inputName, inputValue) => {
this.setState(state => ({
...state,
[inputName]: inputValue // <-- Put square brackets
}))
}
handleFocus = () => this.setState({ isFocused: true })
handleBlur = () => this.setState({ isFocused: true?this.state.entry!='' :true})
handleValueChange = (entry) => this.setState({ entry });
componentDidUpdate() {
Animated.timing(this._animatedIsFocused, {
toValue: this.state.isFocused ? 1 : 0,
duration: 200,
useNativeDriver: true,
}).start();
}
render() {
// console.log(this.state.entry)
const { label, ...props } = this.props;
const { isFocused } = this.state;
const labelStyle = {
position: 'absolute',
left: 0,
top: !isFocused ? 40 : 0,
fontSize: !isFocused ? 16 : 12,
color: 'white',
};
return (
<View style={{ paddingTop: 20,paddingBottom:20 }}>
<Text style={labelStyle}>
{label}
</Text>
<TextInput
{...props}
style={{
height: 50, fontSize: 16, color: 'white', borderBottomWidth: 1, borderBottomColor: "white"
}}
value={this.state.entry}
onChangeText={this.handleValueChange}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
blurOnSubmit
/>
</View>
)
}
}
export default BliszFloatingLabel;
Instead of passing onChangeText like this onChangeText={this.handleValueChange} pass in a callback in BliszFloatingLabel and also in Login component.
onChangeText={(text)=>this.handleValueChange(text)}
Snack with the fixture.
https://snack.expo.io/#waheed25/d16fb3

Declaring array for use in React Native AutoComplete search engine

Not sure where I go about declaring the array with which I want to search from, any assistance would be appreciated. I believe my issue is that I am declaring the "services' array in the incorrect area but I am not sure where else to put it! Or if the commas are the right character to be using in between strings/services
import React, { useState, Component } from 'react';
import { StyleSheet, StatusBar, View, Text, Button, TouchableOpacity } from 'react-native';
import AutoComplete from 'react-native-autocomplete-input';
class CareProviderSequenceScreen extends Component {
constructor (props) {
super (props);
this.state = {
services: [],
query: '',
}
}
render() {
const query = this.state;
const services = {
"Pick up my Prescription",
'Pick up groceries',
'Pick up dry cleaning',
'Pick up my pet',
}
return (
<View style={styles.container}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
containerStyle={styles.autocompleteContainer}
//data to show in suggestion
data={services.length === 1 && comp(query, services[0].title) ? [] : services}
//default value if you want to set something in input
defaultValue={query}
/*onchange of the text changing the state of the query which will trigger
the findFilm method to show the suggestions*/
onChangeText={text => this.setState({ query: text })}
placeholder="Enter your need"
renderItem={({ item }) => (
//you can change the view you want to show in suggestion from here
<TouchableOpacity onPress={() => this.setState({ query: item.title })}>
<Text style={styles.itemText}>
{item.title} ({item.release_date})
</Text>
</TouchableOpacity>
)}
/>
<View style={styles.descriptionContainer}>
{services.length > 0 ? (
<Text style={styles.infoText}>{this.state.query}</Text>
) : (
<Text style={styles.infoText}>Enter The Film Title</Text>
)}
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF',
flex: 1,
padding: 16,
marginTop: 40,
},
autocompleteContainer: {
backgroundColor: '#ffffff',
borderWidth: 0,
},
descriptionContainer: {
flex: 1,
justifyContent: 'center',
},
itemText: {
fontSize: 15,
paddingTop: 5,
paddingBottom: 5,
margin: 2,
},
infoText: {
textAlign: 'center',
fontSize: 16,
},
});
export default CareProviderSequenceScreen ;
CareProviderSequenceScreen .navigationOptions = () => ({
title: "Home & Personal Care",
headerTintColor: '#9EBBD7',
headerStyle: {
height: 65,
backgroundColor: '#1E5797',
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 1,
},
shadowOpacity: 0.20,
shadowRadius: 1.41,
elevation: 2,}
});
First, you are assigning an object to services array.
Second, you are not accessing the query state properly. It should be
const { query } = this.state

Categories

Resources