Center buttons in flex in Appbar - material-ui

I have trouble aligning/justifying as centered buttons in the AppBar.
It looks like this (see demo here):
<AppBar position='sticky'>
<Toolbar>
<div className={classes.topMenuBoxes}>
<img className={classes.logoSize} src={LogoFull} alt="logo" ></img>
</div>
<div className={classes.topMenuBoxes}>
<Button className={classes.menuText} color='inherit' >Offer</Button>
<Button className={classes.menuText} color='inherit' >Join</Button>
<Button className={classes.menuText} color='inherit' component={AboutLink}>About us</Button>
</div>
<div className={classes.topMenuBoxes}>
<DropMenu />
</div>
</Toolbar>
</AppBar>
...and using this makeStyles:
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
},
logoSize: {
marginTop: '30px',
height: '70px',
},
menuButton: {
[theme.breakpoints.up('md')]: {
display: 'none',
},
marginRight: theme.spacing(2),
},
menuText: {
[theme.breakpoints.down('sm')]: {
display: "none",
},
textTransform: 'none',
},
topMenuBoxes: {
flex: 1,
},
}));
How do I align content inside the divs where I have referenced classes.topMenuBoxes?
Thanks!

Add textAlign:"center" to your topMenuBoxes:
const useStyles = makeStyles(theme => ({
// ...
topMenuBoxes: {
flex: 1,
textAlign: "center"
}
}));

Related

center input text in a mui TextField

My TextField input wont center. I am using mui TextField to build a form.
Can anyone help, I have been trying a few different things but I can get it to work.
<TextField
size="small"
id="username"
placeholder="Username"
type="email"
value={values.username}
error={touched.username && !!errors.username}
helperText={touched.username ? errors.username : ''}
onChange={handleChange('username')}
onBlur={handleBlur('username')}
variant="outlined"
InputProps={{ className: classes.input }}
/>
const useStyles = makeStyles(() => ({
input: {
display: 'flex',
justifyContent: 'center',
textAlign: 'center',
},
inputCenter: {
textAlign: 'center',
color: 'red',
},
}));
If you are using MUI v5 I think for text alignment you can use sx prop of mui :
<TextField
InputProps={{
sx: {
"& input": {
textAlign: "center"
}
}
}}
/>
reference : The sx prop
Or if you are using MUI v4 try :
inputProps={{
style: { textAlign: "center" }
}}

Display all row instead of 3 row

Goal:
Display all row in the in table at the same time.
Problem:
It display only 3 row at the same time in the table.
I would like to display all row at the same time without any limitation.
It doesn't work to use "height: '100%'"
Any idea?
Codesandbox:
https://codesandbox.io/s/mkd4dw?file=/demo.tsx
Thank you!
demo.tsx
import * as React from 'react';
import Box from '#mui/material/Box';
import Rating from '#mui/material/Rating';
import {
DataGrid,
GridRenderCellParams,
GridColDef,
useGridApiContext,
} from '#mui/x-data-grid';
function renderRating(params: GridRenderCellParams<number>) {
return <Rating readOnly value={params.value} />;
}
function RatingEditInputCell(props: GridRenderCellParams<number>) {
const { id, value, field } = props;
const apiRef = useGridApiContext();
const handleChange = (event: React.SyntheticEvent, newValue: number | null) => {
apiRef.current.setEditCellValue({ id, field, value: newValue });
};
const handleRef = (element: HTMLSpanElement) => {
if (element) {
const input = element.querySelector<HTMLInputElement>(
`input[value="${value}"]`,
);
input?.focus();
}
};
return (
<Box sx={{ display: 'flex', alignItems: 'center', pr: 2 }}>
<Rating
ref={handleRef}
name="rating"
precision={1}
value={value}
onChange={handleChange}
/>
</Box>
);
}
const renderRatingEditInputCell: GridColDef['renderCell'] = (params) => {
return <RatingEditInputCell {...params} />;
};
export default function CustomEditComponent() {
return (
<div style={{ height: 250, width: '100%' }}>
<DataGrid
rows={rows}
columns={columns}
experimentalFeatures={{ newEditingApi: true }}
/>
</div>
);
}
const columns = [
{
field: 'places',
headerName: 'Places',
width: 120,
},
{
field: 'rating',
headerName: 'Rating',
renderCell: renderRating,
renderEditCell: renderRatingEditInputCell,
editable: true,
width: 180,
type: 'number',
},
];
const rows = [
{ id: 1, places: 'Barcelona', rating: 5 },
{ id: 2, places: 'Rio de Janeiro', rating: 4 },
{ id: 3, places: 'London', rating: 3 },
{ id: 4, places: 'New York', rating: 2 },
];
You need to make use of autoHeight prop supported by the <DataGrid /> component, update your DataGrid component usage to this:
<DataGrid
autoHeight
rows={rows}
columns={columns}
experimentalFeatures={{ newEditingApi: true }}
/>
Reference: https://mui.com/x/react-data-grid/layout/#auto-height

[React-Native-Modal]: onBackButtonPress prop returns nothing

I was trying to customize my Modal with onBackButtonPress prop. To check if it worked or not, I passed a console.log to it like this:
<Modal onBackButtonPress={() => console.log('Something')}>
<NewRidesModal
//...
/>
</Modal>
But in fact, it doesn't even return anything whenever I press the Android back button.
Why is he prop not returning any value at all? Is it deprecated?
I use this library too react-native-modal and onBackButtonPress is working fine.
I face another issue, in my case onBackdropPress is not working, but after I fix my styling modal, everything working fine.
This is my example,
Modal js
import React, { Component } from 'react'
import { View, Text, Image, TouchableOpacity } from 'react-native'
import styles from '../styles/StyleComponentModalProduct'
import { withNavigation } from 'react-navigation'
import Price from '../../../assets/components/price/Price'
import Modal from 'react-native-modal'
class ComponentModalProduct extends Component {
constructor(props) {
super(props)
this.state = {}
}
render() {
return (
<Modal
useNativeDriver={true}
animationIn={'fadeIn'}
animationOut={'fadeOut'}
backdropColor={'rgba(0, 0, 0, 0.7)'}
backdropOpacity={0.5}
isVisible={this.props.showProduct}
onSwipeComplete={() => this.props.close()}
swipeDirection={['down']}
style={{ justifyContent: 'flex-end', margin: 0 }}
onBackButtonPress={() => this.props.close()}
onBackdropPress={() => this.props.close()}>
<View style={styles.container}>
<View style={styles.subContainer}>
<View style={styles.headerContainer}>
<TouchableOpacity
onPress={() => this.props.close()}
style={styles.closButton}
/>
<View style={styles.containerImageProfile}>
<Image
resizeMode={'contain'}
style={styles.imageProfile}
source={{ uri: this.props.selectedProduct.foto }}
/>
</View>
<View style={styles.containerProfile}>
<View style={styles.containerTextName}>
<Text style={styles.textName}>
{this.props.selectedProduct.nama_produk}
</Text>
</View>
<Price
value={this.props.selectedProduct.harga_beli}
style={styles.textProfesi}
/>
</View>
</View>
</View>
</View>
</Modal>
)
}
}
export default withNavigation(ComponentModalProduct)
Style Modal js
import { StyleSheet, Dimensions } from 'react-native'
import { color } from '../../../assets/styles/ColorList'
import {
responsiveHeight,
responsiveFontSize,
responsiveWidth
} from 'react-native-responsive-dimensions'
const windowHeight = Dimensions.get('window').height
const styles = StyleSheet.create({
container: {
justifyContent: 'flex-end',
alignItems: 'center'
},
subContainer: {
height: windowHeight / 2,
backgroundColor: color.whiteColor,
width: '100%',
borderTopRightRadius: 20,
borderTopLeftRadius: 20,
paddingHorizontal: responsiveWidth(5),
paddingVertical: responsiveHeight(3)
},
headerContainer: {
justifyContent: 'center',
alignItems: 'center'
},
closButton: {
backgroundColor: '#E7E7E7',
height: 8,
width: 100,
marginVertical: 10
},
containerImageProfile: {
marginVertical: 10,
width: '100%',
justifyContent: 'center',
alignItems: 'center'
},
imageProfile: {
height: windowHeight / 3.5,
width: '90%',
borderRadius: 20
},
containerProfile: {
justifyContent: 'center',
alignItems: 'center'
},
containerTextName: {
marginHorizontal: responsiveWidth(10),
justifyContent: 'center'
},
textName: {
fontSize: responsiveFontSize(2.5),
color: color.fontColor,
textAlign: 'center'
},
textProfesi: {
fontSize: responsiveFontSize(2.5),
color: color.fontColor,
fontWeight: 'bold'
}
})
export default styles
I found out that onBackButtonPress is deprecated or it was actually removed. There should some more information about this on the documentation.

Echarts - Scrollbar outside the canvas

I am using echarts library for bar charts. I want scrollbar to display outside the canvas. Is there any way I can accomplish this?
Unfortunately, Echarts don't support scrollbar option.
However you can simply achieve this use a wrap DOM.
check this demo:
let echartsObj = echarts.init(document.querySelector('#canvas1'));
option = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [120, 200, 150, 80, 70, 110, 130],
type: 'bar'
}]
};
echartsObj.setOption(option)
echartsObj = echarts.init(document.querySelector('#canvas2'));
option = {
xAxis: {},
yAxis: {},
series: [{
symbolSize: 20,
data: [
[10.0, 8.04],
[8.0, 6.95],
[13.0, 7.58],
[9.0, 8.81],
[11.0, 8.33],
[14.0, 9.96],
[6.0, 7.24],
[4.0, 4.26],
[12.0, 10.84],
[7.0, 4.82],
[5.0, 5.68]
],
type: 'scatter'
}]
};
echartsObj.setOption(option)
.echart-wrap {
display: inline-block;
width: 300px;
height: 300px;
overflow: scroll;
border: 1px solid black;
}
<html>
<header>
<script src="https://cdn.bootcss.com/echarts/4.1.0.rc2/echarts-en.min.js"></script>
</header>
<body>
<div class="echart-wrap">
<div id="canvas1" style="width: 500px; height: 500px">
</div>
</div>
<div class="echart-wrap">
<div id="canvas2" style="width: 500px; height: 500px">
</div>
</div>
</body>
</html>

How to pass input value to form onSubmit without using state in component that renders multiple forms?

This is a bit of a longwinded problem and giving me a ton of headache to solve.
I'm making a voting app. On the page there will be a list of polls on which you can vote. Each poll is a form consisting of input radio buttons representing the different options available for that poll.
What I was doing previously was saving the option you choose to component state in this.state.value and then passing it as an argument to an action creator when the form is submitted.
Problem with this approach is that if I click an option of one poll, and then click submit on another poll, I've actually submitted the wrong option to the wrong poll.
Is there a way to pass input value to form onSubmit without storing it in component state?
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import Loading from '../Loading';
class MyPolls extends Component {
constructor(props) {
super(props);
this.state = {
skip: 0,
isLoading: true,
isLoadingMore: false,
value: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.props.fetchMyPolls(this.state.skip)
.then(() => {
setTimeout(() => {
this.setState({
skip: this.state.skip + 4,
isLoading: false
});
}, 1000);
});
}
sumVotes(acc, cur) {
return acc.votes + cur.votes
}
loadMore(skip) {
this.setState({ isLoadingMore: true });
setTimeout(() => {
this.props.fetchMyPolls(skip)
.then(() => {
const nextSkip = this.state.skip + 4;
this.setState({
skip: nextSkip,
isLoadingMore: false
});
});
}, 1000);
}
handleSubmit(title, e) {
// console.log(e.target);
e.preventDefault();
const vote = {
title,
option: this.state.value
};
console.log(vote)
}
handleChange(event) {
this.setState({ value: event.target.value });
}
renderPolls() {
return this.props.polls.map(poll => {
return (
<div
className='card'
key={poll._id}
style={{ width: '350px', height: '400px' }}>
<div className='card-content'>
<span className='card-title'>{poll.title}</span>
<p>
Total votes: {poll.options.reduce((acc, cur) => { return acc + cur.votes }, 0)}
</p>
<form onSubmit={e => this.handleSubmit(poll.title, e)}>
{poll.options.map(option => {
return (
<p key={option._id}>
<input
name={poll.title}
className='with-gap'
type='radio'
id={option._id}
value={option.option}
onChange={this.handleChange}
/>
<label htmlFor={option._id}>
{option.option}
</label>
</p>
)
})}
<button
type='text'
className='activator teal btn waves-effect waves-light'
style={{
position: 'absolute',
bottom: '10%',
transform: 'translateX(-50%)'
}}
>
Submit
<i className='material-icons right'>
send
</i>
</button>
</form>
</div>
<div className='card-reveal'>
<span className='card-title'>{poll.title}
<i className='material-icons right'>close</i>
</span>
<p>
dsfasfasdf
</p>
</div>
</div>
)
})
}
render() {
return (
<div className='center-align container'>
<h2>My Polls</h2>
{this.state.isLoading ? <Loading size='big' /> :
<div
style={{
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-evenly',
alignItems: 'center',
alignContent: 'center'
}}>
{this.renderPolls()}
</div>}
<div className='row'>
{this.state.isLoadingMore ? <Loading size='small' /> :
<button
className='btn red lighten-2 wave-effect waves-light' onClick={() => this.loadMore(this.state.skip)}>
Load More
</button>}
</div>
</div>
);
}
}
function mapStateToProps({ polls }) {
return { polls }
}
export default connect(mapStateToProps, actions)(MyPolls);
App demo: https://voting-app-drhectapus.herokuapp.com/
(use riverfish#gmail.com and password 123 to login)
Github repo: https://github.com/drhectapus/voting-app
I'm open to any suggestions. Thanks!
The more "React'ish" pattern would be to break it down to more components.
a Poll is a component, a PollOption could be a component as well.
Where each can handle the state internally.
This will allow you to keep global state in your App or some other state manager like redux that will hold all of your polls and each can reference to the selected option (id).
Another thing worth pointing, is that you tend to pass a new function reference on each render call.
For example:
onSubmit={e => this.handleSubmit(poll.title, e)}
This is considered as bad practice because you can interfere with the Reconciliation and The Diffing Algorithm of react.
When you break it down to components that each can fire back a callback with its
props, then you don't need to pass the handler this way.
Here is a small example with your data:
const pollsFromServer = [
{
_id: "5a0d308a70f4b10014994490",
title: "Cat or Dog",
_user: "59f21388843e737de3738a3a",
__v: 0,
dateCreated: "2017-11-16T06:30:34.855Z",
options: [
{ option: "Cat", _id: "5a0d308a70f4b10014994492", votes: 0 },
{ option: "Dog", _id: "5a0d308a70f4b10014994491", votes: 0 }
]
},
{
_id: "5a0c7941e655c22b8cce43d7",
title: "Blonde or Brunette?",
_user: "59f21388843e737de3738a3a",
__v: 0,
dateCreated: "2017-11-15T17:28:33.909Z",
options: [
{ option: "Blonde", _id: "5a0c7941e655c22b8cce43d9", votes: 0 },
{ option: "Brunette", _id: "5a0c7941e655c22b8cce43d8", votes: 0 }
]
},
{
_id: "5a0c7924e655c22b8cce43d4",
title: "Coke or Pepsi",
_user: "59f21388843e737de3738a3a",
__v: 0,
dateCreated: "2017-11-15T17:28:04.119Z",
options: [
{ option: "Coke", _id: "5a0c7924e655c22b8cce43d6", votes: 0 },
{ option: "Pepsi", _id: "5a0c7924e655c22b8cce43d5", votes: 0 }
]
},
{
_id: "5a0c78c2e655c22b8cce43d0",
title: "Favourite german car?",
_user: "59f21388843e737de3738a3a",
__v: 0,
dateCreated: "2017-11-15T17:26:26.724Z",
options: [
{ option: "BMW", _id: "5a0c78c2e655c22b8cce43d3", votes: 0 },
{ option: "Mercedes", _id: "5a0c78c2e655c22b8cce43d2", votes: 0 },
{ option: "Audi", _id: "5a0c78c2e655c22b8cce43d1", votes: 0 }
]
}
];
class Poll extends React.Component {
onSubmit = optionId => {
const { pollId, onSubmit } = this.props;
onSubmit(pollId, optionId);
};
render() {
const { title, options, selectedOption } = this.props;
return (
<div>
<h3>{title}</h3>
<ul>
{options.map((o, i) => {
return (
<PollOption
isSelected={selectedOption === o._id}
onClick={this.onSubmit}
name={o.option}
optionId={o._id}
/>
);
})}
</ul>
</div>
);
}
}
class PollOption extends React.Component {
onClick = () => {
const { optionId, onClick } = this.props;
onClick(optionId);
};
render() {
const { name, isSelected } = this.props;
const selectedClass = isSelected ? "selected" : '';
return (
<li
className={`poll-option ${selectedClass}`}
onClick={this.onClick}
>
{name}
</li>
);
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
polls: pollsFromServer,
submittedPolls: []
};
}
onPollSubmit = (pollId, optionId) => {
this.setState({
submittedPolls: {
...this.state.submittedPolls,
[pollId]: optionId
}
});
};
render() {
const { polls, submittedPolls } = this.state;
return (
<div>
{polls.map((p, i) => {
const selectedPoll = submittedPolls[p._id];
return (
<Poll
selectedOption={selectedPoll}
pollId={p._id}
onSubmit={this.onPollSubmit}
title={p.title}
options={p.options}
/>
);
})}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
.poll-option{
cursor: pointer;
display: inline-block;
box-shadow: 0 0 1px 1px #333;
padding: 15px;
}
.selected{
background-color: green;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>