React: make boxes same size even with different content - css

I have written a website which you can see here: https://konekto.world/
After the onboarding you will notice that the size of the nearly white outer box is different on every screen (especially at https://konekto.world/emergency_details). I want to have a fixed height for the box (which I might even want to make dependent on the screen size). Could you help me where and how in my code I could make the code the same size. What I did until now has the following effect: https://konekto-k8x5umx6o.now.sh
Emergencydetails/index.js
import React from 'react';
import axios from 'axios';
import { withRouter } from 'react-router-dom';
import { withStyles } from '#material-ui/core/styles';
import { Container, Grid } from '#material-ui/core';
import { Header } from '../Layout';
import FormPersonType from './FormPersonType';
import FormEmergencyType from './FormEmergencyType';
import Textbox from './Textbox';
import AppContext from '../utils/AppContext';
import CONST from '../utils/Constants';
import ProgressiveMobileStepper from './ProgressiveMobileStepper';
const styles = theme => ({
containerWhenIPhone: {
alignItems: 'center',
height: '515.5px',
//width: '414.4px',
maxWidth: 'sm',
border: 'black',
'border-width': 'medium',
'margin-top': '50px',
background: 'rgba(255, 255, 255, 0.8)',
'border-radius': '20px'
},
container: {
alignItems: 'center',
height: '60%',
border: 'black',
'border-width': 'medium',
'margin-top': '50px',
background: 'rgba(255, 255, 255, 0.8)',
'border-radius': '20px'
},
item: {
width: '100%',
'text-align': 'center',
'border-radius': '5px',
'margin-top': '5px',
'justify-content': 'center'
},
container2: {
border: 'black',
'border-width': 'medium',
'margin-top': '30px'
},
picture: { display: 'block', margin: '0 auto' },
box: { width: '230px' }
});
class SOS extends React.Component {
static contextType = AppContext;
constructor(props) {
super(props);
this.state = {
timerOn: false,
componentType: 'type_of_emergency', //type_of_person //texbox
ambulance: false,
fire_service: false,
police: false,
car_service: false,
meAffected: false,
anotherPerson: false,
activeStep: 0
};
this.classes = props.classes;
this.handleNext = this.handleNext.bind(this);
this.handleBack = this.handleBack.bind(this);
this.handleEmergencyType = this.handleEmergencyType.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
showSettings(event) {
event.preventDefault();
}
handleNext(e) {
if (this.state.componentType === 'type_of_emergency') {
this.setState({ componentType: 'type_of_person' });
} else if (this.state.componentType === 'type_of_person')
this.setState({ componentType: 'textbox' });
else if (this.state.componentType === 'textbox') {
this.props.history.push('/transmitted_data');
}
this.setState({ activeStep: this.state.activeStep + 1 });
}
handleBack(e) {
if (this.state.componentType === 'textbox') {
this.setState({ componentType: 'type_of_person' });
} else if (this.state.componentType === 'type_of_person') {
this.setState({ componentType: 'type_of_emergency' });
} else if (this.state.componentType === 'type_of_emergency') {
this.props.history.push('/emergency_sent');
}
this.setState({ activeStep: this.state.activeStep - 1 });
}
handleEmergencyType(new_emergency_state) {
console.log(new_emergency_state);
this.setState(new_emergency_state);
}
onSubmit(e) {
console.log('in OnSubmit');
axios
.post(CONST.URL + 'emergency/create', {
id: 1,
data: this.state
})
.then(res => {
console.log(res);
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
render() {
let component;
if (this.state.componentType === 'type_of_emergency') {
component = (
<FormEmergencyType
handleComponentType={this.handleComponentType}
handleEmergencyType={this.handleEmergencyType}
emergencyTypes={this.state}
timerStart={this.timerStart}
onSubmit={this.onSubmit}
/>
);
} else if (this.state.componentType === 'type_of_person') {
component = (
<FormPersonType
handleComponentType={this.handleComponentType}
personTypes={this.state}
/>
);
} else if (this.state.componentType === 'textbox') {
component = <Textbox handleFinished={this.handleFinished} />;
}
return (
<React.Fragment>
<Header title="Specify Details" BackButton="true" />
<Container
component="main"
className={this.classes.containerWhenIPhone}
>
<Grid
container
className={this.classes.container}
direction="column"
spacing={2}
>
<Grid item sm={12} className={this.classes.item}>
{component}
</Grid>
</Grid>
<Grid
container
className={this.classes.container2}
direction="column"
spacing={2}
>
<Grid item sm={12} className={this.classes.item}>
<ProgressiveMobileStepper
handleNext={this.handleNext}
handleBack={this.handleBack}
activeStep={this.state.activeStep}
/>
</Grid>
</Grid>
</Container>
</React.Fragment>
);
}
}
export default withRouter(withStyles(styles)(SOS));
// <Container component="main" maxWidth="sm">
I conditionally render the FormPersonType, FormEmergencyType, and Textbox but they donĀ“t contain any styling.
Thank you for your help!

Add the min-height: 60vh, instead of height: 60%, that will work with the fixed height.
also for the container-child fix:
.containerWhenIPhone{
overflow: auto;
box-sizing: content-box;
}

Related

How to change styles in Table Pagination Material-ui v.5.0 with React

I'm trying to change the width, height and color of table pagination on Material-ui V5.0 with React, but it does not accept classes. As the pagination uses .MuiToolbar-root, if I make changes with a .css file, it brakes my MuiToolbar at the top of the App page. How should I apply the changes needed without braking the Appbar at the top? Also, I will need to change the padding of .MuiTableCell-root as well. I'm sending my code bellow. Please all helps will be very appreciated.
// Component SupplierTable
import React, {useState} from 'react'
import './SupplierTable.css';
import SupplierForm from './SupplierForm';
import PageHeader from '../components/PageHeader';
import FactoryIcon from '#mui/icons-material/Factory';
import * as supplierService from '../services/EmployeeService';
import Controls from "../components/controls/Controls";
import { InputAdornment } from '#mui/material';
import SearchIcon from '#mui/icons-material/Search';
import AddIcon from '#mui/icons-material/Add';
import Box from '#mui/material/Box';
import Paper from '#mui/material/Paper';
import useTable from "../components/useTable";
import { makeStyles } from '#mui/styles';
import ModeEditOutlineIcon from '#mui/icons-material/ModeEditOutline';
import { TableRow, TableBody, TableCell } from '#mui/material';
import CloseIcon from '#mui/icons-material/Close';
import Popup from '../components/Poup';
import Notification from '../components/Notifications';
import ConfirmDialog from '../components/ConfirmDialog';
import Grid from '#mui/material/Grid';
const useStyles = makeStyles(theme => ({
overrides: {
'&.MuiTablePagination-root':{
width: '960px',
height: '35px',
backgroundColor: '#a9aeb3',
color: 'rgb(41, 39, 39)',
fontFamily: 'Arial, Helvetica, sansSerif',
fontWeight: '700',
}
},
pageContent: {
margin: theme.spacing(1),
padding: theme.spacing(3)
},
searchInput: {
width: '50%'
},
newButton: {
position: 'absolute',
right: '0px'
},
}));
const headCells = [
{ id: 'fullName', label: 'Employee Name' },
{ id: 'email', label: 'Email Address (Personal)' },
{ id: 'mobile', label: 'Mobile Number' },
{ id: 'department', label: 'Department' },
{ id: 'actions', label: 'Actions', disableSorting: true }
]
export default function Supplyer() {
const classes = useStyles();
const [recordForEdit, setRecordForEdit] = useState(null)
const [records, setRecords] = useState(supplierService.getAllSuppliers())
const [filterFn, setFilterFn] = useState({ fn: items => { return items; } })
const [openPopup, setOpenPopup] = useState(false)
const [notify, setNotify] = useState({ isOpen: false, message: '', type: '' })
const [confirmDialog, setConfirmDialog] = useState({ isOpen: false, title: '', subTitle: '' })
const {
TblContainer,
TblHead,
TblPagination,
recordsAfterPagingAndSorting
} = useTable(records, headCells, filterFn);
const handleSearch = e => {
let target = e.target;
setFilterFn({
fn: items => {
if (target.value == "")
return items;
else
return items.filter(x => x.fullName.toLowerCase().includes(target.value))
}
})
}
const addOrEdit = (employee, resetForm) => {
if (employee.id == 0)
supplierService.insertEmployee(employee)
else
supplierService.updateEmployee(employee)
resetForm()
setRecordForEdit(null)
setOpenPopup(false)
setRecords(supplierService.getAllEmployees())
setNotify({
isOpen: true,
message: 'Submitted Successfully',
type: 'success'
})
}
const openInPopup = item => {
setRecordForEdit(item)
setOpenPopup(true)
}
const onDelete = id => {
setConfirmDialog({
...confirmDialog,
isOpen: false
})
supplierService.deleteEmployee(id);
setRecords(supplierService.getAllEmployees())
setNotify({
isOpen: true,
message: 'Deleted Successfully',
type: 'error'
})
}
return (
<>
<PageHeader
title= "Fornecedores"
subTitle="Tabela de Fornecedores - Novo / Atualizar"
icon={<FactoryIcon fontSize="large" text-align='center'/>}
/>
<Box sx={{width: "1060px"}}>
<Paper className={classes.pageContent}>
<Grid container direction= 'row' justifyContent="space-between" >
<Controls.Input
label="Pesquisar Fornecedor"
className={classes.searchInput}
InputProps={{
startAdornment: (<InputAdornment position="start">
<SearchIcon />
</InputAdornment>)
}}
onChange={handleSearch}
/>
<Controls.Button
text="Adicionar"
variant="outlined"
color="primary"
startIcon={<AddIcon />}
className={classes.newButton}
onClick={() => { setOpenPopup(true); setRecordForEdit(null); }}
/>
</Grid>
<TblContainer>
<TblHead />
<TableBody>
{
recordsAfterPagingAndSorting().map(item =>
(<TableRow key={item.id}>
<TableCell>{item.fullName}</TableCell>
<TableCell>{item.email}</TableCell>
<TableCell>{item.mobile}</TableCell>
<TableCell>{item.department}</TableCell>
<TableCell>
<Controls.ActionButton
color="primary"
onClick={() => { openInPopup(item) }}>
<ModeEditOutlineIcon fontSize="small" />
</Controls.ActionButton>
<Controls.ActionButton
color="secondary"
onClick={() => {
setConfirmDialog({
isOpen: true,
title: 'Are you sure to delete this record?',
subTitle: "You can't undo this operation",
onConfirm: () => { onDelete(item.id) }
})
}}>
<CloseIcon fontSize="small" />
</Controls.ActionButton>
</TableCell>
</TableRow>)
)
}
</TableBody>
</TblContainer>
**strong text** // Pagination begins here!!!!!
<TblPagination components={{
Toolbar: props => (
<div>
style={{ backgroundColor: '#a9aeb3', width: '950px', color: 'rgb(41, 39, 39)',
height: '35px' }}
</div>
)
}}/>
</Paper>
</Box>
<Popup
title="Employee Form"
openPopup={openPopup}
setOpenPopup={setOpenPopup}
>
<SupplierForm
recordForEdit={recordForEdit}
addOrEdit={addOrEdit} />
</Popup>
<Notification
notify={notify}
setNotify={setNotify}
/>
<ConfirmDialog
confirmDialog={confirmDialog}
setConfirmDialog={setConfirmDialog}
/>
</>
)
}
I've been struggling with styling the pagination component myself, but just got it working using sx.
Try with something like this:
<TablePagination
sx={{
'.MuiTablePagination-toolbar': {
backgroundColor: '#a9aeb3',
width: '950px',
color: 'rgb(41, 39, 39)',
height: '35px',
},
}}
/>
Edit:
I tried styling "everything" just to see how it would be done, look here for ideas if there was something else you needed to style.
<Pagination
{...mTablePaginationProps}
rowsPerPage={rowsPerPage}
onRowsPerPageChange={onRowsPerPageSelect}
component="div"
onPageChange={onPageChange}
sx={{
backgroundColor: 'red !important', // gets overridden if not important
height: '70px',
'.MuiInputBase-root': {
backgroundColor: 'green',
},
'.MuiTablePagination-toolbar': {
backgroundColor: 'pink',
width: '950px',
color: 'rgb(41, 39, 39)',
height: '35px',
},
'.MuiBox-root': {
backgroundColor: 'yellow',
color: 'black',
'& .MuiSvgIcon-root': {
backgroundColor: 'purple',
color: 'black',
},
},
}}
SelectProps={{
...mTablePaginationProps.SelectProps,
MenuProps: {
...mTablePaginationProps.SelectProps.MenuProps,
sx: {
'.MuiPaper-root': {
backgroundColor: 'rosybrown',
color: 'black',
},
'.MuiTablePagination-menuItem': {
':hover': {
backgroundColor: 'turquoise',
},
backgroundColor: 'yellow',
},
'.MuiTablePagination-menuItem.Mui-selected': {
':hover': {
backgroundColor: 'blue',
},
backgroundColor: 'purple',
},
},
},
}}
/>
This ends up looking like this:

React Native Keyboard Aware Scroll View Squeezing Content

I was recently working on a React Native project and I choose to use KeyBoardAwareScrollView to handle the keyboard scroll of the screen. The Below image shows the design which should be actual but when I use keyboardAvoidingView it starts to add padding to the bottom of the screen while I want the screen to scroll up when the keyboard is visible, after doing some research I came across the KeyboardAvoidingScrollView but using that if i give they height of
flex: 1
If i change this line to a static height it fixes the issue on a static screen
scrollContainer: { height: 1000 }
to the container that holds the content everything is pushed to the top.
To somehow adjust the view I gave the scroll container fixed height that did solve the problem temporarily but didn't work on all screen sizes.
My Code Looks like this
import {
View,
Text,
StyleSheet,
SafeAreaView,
Image,
StatusBar,
KeyboardAvoidingView,
} from "react-native";
import AuthContent from "../../auth/AuthContent";
import AuthForm from "../../auth/AuthForm";
import CustomTextInput from "../../components/CustomTextInput";
import { setEmailPass } from "../../../redux/UserReucer";
import { useDispatch } from "react-redux";
import { useSelector } from "react-redux";
import { ImageBackground } from "react-native";
import { GlobalStyles } from "../../../consts/GlobalConsts";
import OrientationLoadingOverlay from "react-native-orientation-loading-overlay";
import { useState } from "react";
import Loading from "../../components/Loading";
import { getAxiosClient } from "../../apis/TallyApi";
import { showAlert } from "../../../utils/Alert";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
const SignUpScreen = ({ navigation }) => {
const dispatch = useDispatch();
const currentUser = useSelector((state) => {
return state.mUser;
});
const [isLoading, setIsLoading] = useState(false);
// console.log("Redux state", currentUser);
async function loginHandler({ email, password }) {
setIsLoading(true);
console.log("Signup Screen", email, password);
try {
let response = await getAxiosClient().post("/users/checkEmail", {
email: email,
});
dispatch(setEmailPass({ email, password }));
navigation.navigate("RoleScreen");
console.log("Axios response ", response.data);
} catch (err) {
// const { response } = err;
// const { request, ...errorObject } = response;
console.log("Axios Error ", err.response.data.message);
showAlert(err.response.data.message);
// console.error(err);
// console.error(err);
} finally {
setIsLoading(false);
}
}
return (
<>
<ImageBackground
source={require("../../../../assets/background_color.png")}
style={GlobalStyles.backgroundContainer}
>
<SafeAreaView style={styles.container}>
<KeyboardAwareScrollView
style={styles.container}
behavior={Platform.OS === "ios" ? "padding" : "height"}
>
<View style={styles.scrollContainer}>
<StatusBar barStyle="light-content" />
<View style={styles.topSpace}></View>
<View style={styles.mainContainer}>
<View style={styles.imageContainer}>
<Image
style={styles.image}
source={require("../../../../assets/email_icn.png")}
></Image>
</View>
<View style={styles.textContainer}>
<Text style={styles.largeText}>Continue with email</Text>
<Text style={styles.smallText}>
Enter your email address to get register with palace
</Text>
</View>
<View style={styles.authContainer}>
<AuthContent
styles={styles.authContainer}
onAuthenticate={loginHandler}
></AuthContent>
</View>
</View>
<View style={styles.bottomSpace}></View>
<Loading isLoading={isLoading}></Loading>
</View>
</KeyboardAwareScrollView>
</SafeAreaView>
</ImageBackground>
</>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
scrollContainer: { flex: 1 },
largeText: {
fontSize: 30,
color: "white",
marginVertical: 9,
textAlign: "center",
},
smallText: {
fontSize: 16,
color: "white",
marginVertical: 9,
textAlign: "center",
},
topSpace: {
flex: 0.5,
},
mainContainer: {
flex: 8.5,
},
bottomSpace: {
flex: 1,
},
imageContainer: {
flex: 3,
alignItems: "center",
justifyContent: "center",
},
textContainer: {
flex: 1.5,
justifyContent: "center",
},
authContainer: {
flex: 2.5,
},
image: {
resizeMode: "contain",
height: "90%",
},
});
export default SignUpScreen;
Just use a <ScrollView> rather than <KeyboardAwareScrollView>

Is there a way to hide scrollbar in Material UI Table sticky header?

I have a Material-UI Table with a fixed header in a React project (reference: https://material-ui.com/components/tables/#fixed-header). I would like to hide the scrollbar in the table header (which overlaps it), while still showing it in the table body.
I have mostly tried changing the overflow property in the TableContainer, Table, TableHead, and TableBody components, though with poor results. Searching around a bit, it seemed that this problem could be solved setting the display property of the aforementioned components to block. However, this approach let me only move the scrollbar from the TableContainer component to the Table component, not solving the issue and messing up the table layout.
Edit
Working example:
Wanted Beahviour
If you are using makeStyles from material ui like the example you can add :
const useStyles = makeStyles({
root: {
width: '100%',
},
container: {
scrollbarWidth: "none" /* Firefox */,
maxHeight: 440,
"&::-webkit-scrollbar": {
display: "none"
} /* Chrome */
}
});
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { styled } from '#mui/material/styles';
import TableCell from '#mui/material/TableCell';
import Paper from '#mui/material/Paper';
import { AutoSizer, Column, Table } from 'react-virtualized';
const classes = {
flexContainer: 'ReactVirtualizedDemo-flexContainer',
tableRow: 'ReactVirtualizedDemo-tableRow',
tableRowHover: 'ReactVirtualizedDemo-tableRowHover',
tableCell: 'ReactVirtualizedDemo-tableCell',
noClick: 'ReactVirtualizedDemo-noClick',
};
const styles = ({ theme }) => ({
// temporary right-to-left patch, waiting for
// https://github.com/bvaughn/react-virtualized/issues/454
'& .ReactVirtualized__Table__headerRow': {
...(theme.direction === 'rtl' && {
paddingLeft: '0 !important',
}),
...(theme.direction !== 'rtl' && {
paddingRight: undefined,
}),
},
[`& .${classes.flexContainer}`]: {
display: 'flex',
alignItems: 'center',
boxSizing: 'border-box',
},
[`& .${classes.tableRow}`]: {
cursor: 'pointer',
},
[`& .${classes.tableRowHover}`]: {
'&:hover': {
backgroundColor: theme.palette.grey[200],
},
},
[`& .${classes.tableCell}`]: {
flex: 1,
},
[`& .${classes.noClick}`]: {
cursor: 'initial',
},
});
class MuiVirtualizedTable extends React.PureComponent {
static defaultProps = {
headerHeight: 48,
rowHeight: 48,
};
getRowClassName = ({ index }) => {
const { onRowClick } = this.props;
return clsx(classes.tableRow, classes.flexContainer, {
[classes.tableRowHover]: index !== -1 && onRowClick != null,
});
};
cellRenderer = ({ cellData, columnIndex }) => {
const { columns, rowHeight, onRowClick } = this.props;
return (
<TableCell
component="div"
className={clsx(classes.tableCell, classes.flexContainer, {
[classes.noClick]: onRowClick == null,
})}
variant="body"
style={{ height: rowHeight }}
align={
(columnIndex != null && columns[columnIndex].numeric) || false
? 'right'
: 'left'
}
>
{cellData}
</TableCell>
);
};
headerRenderer = ({ label, columnIndex }) => {
const { headerHeight, columns } = this.props;
return (
<TableCell
component="div"
className={clsx(classes.tableCell, classes.flexContainer, classes.noClick)}
variant="head"
style={{ height: headerHeight }}
align={columns[columnIndex].numeric || false ? 'right' : 'left'}
>
<span>{label}</span>
</TableCell>
);
};
render() {
const { columns, rowHeight, headerHeight, ...tableProps } = this.props;
return (
<AutoSizer>
{({ height, width }) => (
<Table
height={height}
width={width}
rowHeight={rowHeight}
gridStyle={{
direction: 'inherit',
}}
headerHeight={headerHeight}
{...tableProps}
rowClassName={this.getRowClassName}
>
{columns.map(({ dataKey, ...other }, index) => {
return (
<Column
key={dataKey}
headerRenderer={(headerProps) =>
this.headerRenderer({
...headerProps,
columnIndex: index,
})
}
className={classes.flexContainer}
cellRenderer={this.cellRenderer}
dataKey={dataKey}
{...other}
/>
);
})}
</Table>
)}
</AutoSizer>
);
}
}
MuiVirtualizedTable.propTypes = {
columns: PropTypes.arrayOf(
PropTypes.shape({
dataKey: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
numeric: PropTypes.bool,
width: PropTypes.number.isRequired,
}),
).isRequired,
headerHeight: PropTypes.number,
onRowClick: PropTypes.func,
rowHeight: PropTypes.number,
};
const VirtualizedTable = styled(MuiVirtualizedTable)(styles);
// ---
const sample = [
['Frozen yoghurt', 159, 6.0, 24, 4.0],
['Ice cream sandwich', 237, 9.0, 37, 4.3],
['Eclair', 262, 16.0, 24, 6.0],
['Cupcake', 305, 3.7, 67, 4.3],
['Gingerbread', 356, 16.0, 49, 3.9],
];
function createData(id, dessert, calories, fat, carbs, protein) {
return { id, dessert, calories, fat, carbs, protein };
}
const rows = [];
for (let i = 0; i < 200; i += 1) {
const randomSelection = sample[Math.floor(Math.random() * sample.length)];
rows.push(createData(i, ...randomSelection));
}
export default function ReactVirtualizedTable() {
return (
<Paper style={{ height: 400, width: '100%' }}>
<VirtualizedTable
rowCount={rows.length}
rowGetter={({ index }) => rows[index]}
columns={[
{
width: 200,
label: 'Dessert',
dataKey: 'dessert',
},
{
width: 120,
label: 'Calories\u00A0(g)',
dataKey: 'calories',
numeric: true,
},
{
width: 120,
label: 'Fat\u00A0(g)',
dataKey: 'fat',
numeric: true,
},
{
width: 120,
label: 'Carbs\u00A0(g)',
dataKey: 'carbs',
numeric: true,
},
{
width: 120,
label: 'Protein\u00A0(g)',
dataKey: 'protein',
numeric: true,
},
]}
/>
</Paper>
);
}
enter link description here

TypeError: navigation.getParam is not a function - react native

This is the error I get-->
I have a HomeFeed.js where I list all my articles and when you click on each article you get taken to the Content.js where you can see the article details/content.
In the HomeFeed.js, when you press on the article this happens-->
..........................................................................................................................................................................................................................................................................................................................................................................................
onPress={() => {
this.props.navigation.navigate("Content", {
articlekey: `${JSON.stringify(item.key)}`,
});
}}
..........................................................................................................................................................................................................................................................................................................................................................................................
In my Content.js, I have the below:
import React, { Component } from "react";
import { StyleSheet, ScrollView, ActivityIndicator, View } from "react-native";
import { Text, Card } from "react-native-elements";
import firebase from "../../firebase";
class Content extends Component {
static navigationOptions = {
title: "Content",
};
constructor() {
super();
this.state = {
isLoading: true,
article: {},
key: "",
};
}
componentDidMount() {
const { navigation } = this.props;
const ref = firebase
.firestore()
.collection("articles")
.doc(JSON.parse(navigation.getParam("articlekey")));
ref.get().then((doc) => {
if (doc.exists) {
this.setState({
article: doc.data(),
key: doc.id,
isLoading: false,
});
} else {
console.log("No such document!");
}
});
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.activity}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
);
}
return (
<ScrollView>
<Card style={styles.container}>
<View style={styles.subContainer}>
<View>
<Text h3>{this.state.article.title}</Text>
</View>
<View>
<Text h5>{this.state.article.content}</Text>
</View>
</View>
</Card>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20,
},
subContainer: {
flex: 1,
paddingBottom: 20,
borderBottomWidth: 2,
borderBottomColor: "#CCCCCC",
},
activity: {
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: "center",
justifyContent: "center",
},
detailButton: {
marginTop: 10,
},
});
export default Content;
The problem is with your get method of parameters. With react-navigation version 5.X or upper, you need to get params with route.
SOLUTION
Change componentDidMount( ) like this
componentDidMount() {
// const { navigation } = this.props; remove this
const { articlekey } = this.props.route.params; //add this
const ref = firebase
.firestore()
.collection("articles")
.doc(JSON.parse(articlekey));
ref.get().then((doc) => {
if (doc.exists) {
this.setState({
article: doc.data(),
key: doc.id,
isLoading: false,
});
} else {
console.log("No such document!");
}
});
}

Properly pushing a Canvas with Material UI Persistent Drawers

I have an application with two expandable toolbars. The left toolbar functions as intended, but I have not been able to make the right toolbar push the content properly. See the code below.
I copied the exact code from here - see Persistent Drawers: https://material-ui.com/demos/drawers/
The KeyboardListener is display:none and the SceneCanvas element has the following styling:
root: {
height: '100%',
width: '100%',
position: 'relative',
zIndex: 0,
lineHeight: 0,
cursor: 'crosshair',
}
The desired functionality is for both the left and right toolbars to push the content in and resize the canvas and the canvas content. And tips or insight would be greatly appreciated!
import React from 'react';
import classNames from 'classnames';
import { withStyles } from '#material-ui/core/styles';
import Drawer from '#material-ui/core/Drawer';
import AppBar from '#material-ui/core/AppBar';
import Toolbar from '#material-ui/core/Toolbar';
import List from '#material-ui/core/List';
import MenuItem from '#material-ui/core/MenuItem';
import Typography from '#material-ui/core/Typography';
import TextField from '#material-ui/core/TextField';
import Divider from '#material-ui/core/Divider';
import IconButton from '#material-ui/core/IconButton';
import MenuIcon from '#material-ui/icons/Menu';
import ChevronLeftIcon from '#material-ui/icons/ChevronLeft';
import ChevronRightIcon from '#material-ui/icons/ChevronRight';
import SceneCanvas from '../../three/SceneCanvas';
import KeyboardListener from '../KeyboardListener';
const drawerWidth = 240;
const styles = theme => ({
root: {
flexGrow: 1,
},
appFrame: {
height: 430,
zIndex: 1,
overflow: 'hidden',
position: 'relative',
display: 'flex',
width: '100%',
},
appBar: {
position: 'absolute',
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
appBarShift: {
width: `calc(100% - ${drawerWidth}px)`,
transition: theme.transitions.create(['margin', 'width'], {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
},
'appBarShift-left': {
marginLeft: drawerWidth,
},
'appBarShift-right': {
marginRight: drawerWidth,
},
menuButton: {
marginLeft: 12,
marginRight: 20,
},
hide: {
display: 'none',
},
drawerPaper: {
position: 'relative',
width: drawerWidth,
},
drawerHeader: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
padding: '0 8px',
...theme.mixins.toolbar,
},
content: {
flexGrow: 1,
backgroundColor: theme.palette.background.default,
padding: theme.spacing.unit * 3,
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
},
'content-left': {
marginLeft: -drawerWidth,
},
'content-right': {
marginRight: -drawerWidth,
},
contentShift: {
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
},
'contentShift-left': {
marginLeft: 0,
},
'contentShift-right': {
marginRight: 0,
},
});
class Header extends React.Component {
state = {
open: false,
anchor: 'left',
};
handleDrawerOpen = () => {
this.setState({ open: true });
};
handleDrawerClose = () => {
this.setState({ open: false });
};
handleChangeAnchor = (event) => {
this.setState({
anchor: event.target.value,
});
};
render() {
const { classes, theme } = this.props;
const { anchor, open } = this.state;
const drawer = (
<Drawer
variant="persistent"
anchor={anchor}
open={open}
classes={{
paper: classes.drawerPaper,
}}
>
<div className={classes.drawerHeader}>
<IconButton onClick={this.handleDrawerClose}>
{theme.direction === 'rtl' ? <ChevronRightIcon /> : <ChevronLeftIcon />}
</IconButton>
</div>
<Divider />
<List>Testing</List>
<Divider />
<List>Testing</List>
</Drawer>
);
let before = null;
let after = null;
if (anchor === 'left') {
before = drawer;
} else {
after = drawer;
}
return (
<div className={classes.root}>
<TextField
id="persistent-anchor"
select
label="Anchor"
value={anchor}
onChange={this.handleChangeAnchor}
margin="normal"
>
<MenuItem value="left">left</MenuItem>
<MenuItem value="right">right</MenuItem>
</TextField>
<div className={classes.appFrame}>
<AppBar
className={classNames(classes.appBar, {
[classes.appBarShift]: open,
[classes[`appBarShift-${anchor}`]]: open,
})}
>
<Toolbar disableGutters={!open}>
<IconButton
color="inherit"
aria-label="open drawer"
onClick={this.handleDrawerOpen}
className={classNames(classes.menuButton, open && classes.hide)}
>
<MenuIcon />
</IconButton>
<Typography variant="title" color="inherit" noWrap>
Persistent drawer
</Typography>
</Toolbar>
</AppBar>
{before}
<main
className={classNames(classes.content, classes[`content-${anchor}`], {
[classes.contentShift]: open,
[classes[`contentShift-${anchor}`]]: open,
})}
>
<div className={classes.drawerHeader} />
<KeyboardListener />
<SceneCanvas />
</main>
{after}
</div>
</div>
);
}
}
export default withStyles(styles, { withTheme: true })(Header);
Left Toolbar Functioning Properly
Right Toolbar Breaking
Desired Function

Resources