Material-UI Style Override? - material-ui

I'm updating my app from Material-UI v1 to v2. I'm trying to use a style override to set the color of a selected <BottomNavigationAction> element.
const styles = {
bottomNavStyle: {
position: 'fixed',
left: '0px',
bottom: '0px',
height: '50px',
width: '100%',
zIndex: '100'
},
'&$selected': {
color: "#00bcd4" //<==trying to add this color to selected items
},
};
class bottom_nav extends Component {
state = {
selectedIndex: -1,
};
handleChange = (event, value) => {
this.setState({value});
};
render() {
const { classes } = this.props;
return (
<Paper className={classes.bottomNavStyle}>
<BottomNavigation
value={this.props.selectedBottomNavIndex}
onChange={this.handleChange}
showLabels
>
<BottomNavigationAction
label="Appointments"
icon={theApptsIcon}
/>
<BottomNavigationAction
label="Contacts"
icon={theEmailIcon}
/>
<BottomNavigationAction
label="Video Call"
icon={theVideoCall}
/>
</BottomNavigation>
</Paper>
);
}
}
export default withStyles(styles)(bottom_nav);
But, this does not do anything to the color of selected items.
I've read the Material-UI docs on CSS in JS and JSS, but haven't quite gotten it yet. What is the correct syntax for this?
UPDATE
Based on a response to this thread I've tried this:
const styles = {
bottomNavStyle: {
position: 'fixed',
left: '0px',
bottom: '0px',
height: '50px',
width: '100%',
zIndex: '100'
},
actionItemStyle: {
'&$selected': {
color: "#00bcd4 !important"
},
},
}
[.....]
return (
<Paper className={classes.bottomNavStyle}>
<BottomNavigation
value={this.props.selectedBottomNavIndex}
onChange={this.handleChange}
showLabels
>
<BottomNavigationAction
label="Appointments"
icon={theApptsIcon}
className={classes.actionItemStyle}
/>
<BottomNavigationAction
label="Contacts"
icon={theEmailIcon}
className={classes.actionItemStyle}
/>
<BottomNavigationAction
label="Video Call"
icon={theVideoCall}
className={classes.actionItemStyle}
/>
</BottomNavigation>
</Paper>
);
}
...but have not yet gotten the new color to appear on the web page.

Your updated solution looks good, there are just a few small changes...
You need to include an empty .selected class in your styles rules.
const styles = {
// Root styles for `BottomNavigationAction` component
actionItemStyles: {
"&$selected": {
color: "red"
}
},
// This is required for the '&$selected' selector to work
selected: {}
};
You need to pass classes={{selected: classes.selected}} to BottomNavigationAction. This is required for the '&$selected' selector to work.
<BottomNavigation
value={value}
onChange={this.handleChange}
className={classes.root}
>
<BottomNavigationAction
classes={{
root: classes.actionItemStyles,
selected: classes.selected
}}
label="Recents"
value="recents"
icon={<RestoreIcon />}
/>
</BottomNavigation>
Live Example:

There are couple of things I would like to suggest.
1) Write the name of the component with first letter capitalized since it is not treated the same way if it is named with small first letter and with capitalized.
2) If there is no other way for your cs rule to be applied, if it is overridden always because of some css specificity, use !iportant at the end of the rule.
3) Try this type of nesting of css in jss:
const styles = {
bottomNavStyle: {
position: 'fixed',
left: '0px',
bottom: '0px',
height: '50px',
width: '100%',
zIndex: '100',
'&:selected': {
color: "#00bcd4"
},
},
};

Related

AgGrid Custom Cell Editor does not refresh when calling refreshCells()

TLDR; the cell editor does not rerender when we invoke the api.refreshCells method.
The following code renders a simple table with 2 rows. The value of the data is irrelevant since it uses both a custom cell renderer and a custom cell editor that reaches into context to pluck a value.
When context updates we need to call refreshCells, since no change is detected to the actual cell data value.
Note when clicking increment the value of the context is incremented and the value of the cells updates accordingly. Observe the console log messages for each view renderer.
Now double click cell to enter into edit mode and then click the increment button. Note that the cell editor is not re-rendered when the increment takes place.
I can get the editor to update using events but the props (and so the context) are stale.
Presume this is a design decision, but I need to rerender the cell editor component when my context data updates. Any ideas?
https://plnkr.co/edit/3cCRnAY14nOWt3tl?open=index.jsx
const EditRenderer = (props) => {
console.log('render edit cell')
return (
<input
value={props.context.appContext.cellValue}
/>
);
};
const ViewRenderer = (props) => {
console.log('render view cell')
return <React.Fragment>{props.context.appContext.cellValue}</React.Fragment>;
};
const Grid = () => {
const [rowData] = useState([{ number: 10 }, { number: 3 }]);
const columnDefs = useMemo(
() => [
{
field: 'number',
cellEditor: EditRenderer,
cellRenderer: ViewRenderer,
editable: true,
width: 200,
},
],
[]
);
const [context, setContext] = useState({ cellValue: 1 });
const gridApiRef = useRef();
return (
<React.Fragment>
<p>Context value: {JSON.stringify(context)}</p>
<button
onClick={() => {
setContext({ cellValue: context.cellValue += 1 });
gridApiRef.current.refreshCells({force: true});
}}
>
Increment
</button>
<div style={{ width: '100%', height: '100%' }}>
<div
style={{
height: '400px',
width: '200px',
}}
className="ag-theme-alpine test-grid"
>
<AgGridReact
onGridReady={(e) => {
gridApiRef.current = e.api;
}}
context={{ appContext: context }}
columnDefs={columnDefs}
rowData={rowData}
/>
</div>
</div>
</React.Fragment>
);
};
render(<Grid />, document.querySelector('#root'));

Styles not getting applied when I upgrade to Material UI 5 for elements

I recently upgraded my Material UI from V4 to 5 and stuck with a truckload of issues. One of them is that the styles are messing up when i move away from JSS
The arrow icon need to get the styles and the styles are not getting applied.
const StyledPopper = styled(Popper)(({ theme }) => {
return {
[`&.${classes.popper}`]: {
top: "100px !important",
left: "200px !important",
zIndex: 1,
'&[x-placement*="bottom"] $arrow': {
// is not getting applied
marginTop: theme.spacing(-5.25),
"&::before": {
borderWidth: "0 1em 1em 1em",
borderColor: `transparent transparent red transparent`
}
}
},
[`& .${classes.arrow}`]: {
position: "absolute",
"&::before": {
content: '""',
display: "block",
borderStyle: "solid"
}
}
};
});
<StyledPopper
open
placement="bottom-end"
anchorEl={
document && document.getElementById("location-confirmer-desktop")
}
modifiers={{ arrow: { enabled: true, element: arrowRef } }}
className={classes.popper}
>
<Box ref={setArrowRef} className={classes.arrow} />
<Box>This is the content</Box>
</StyledPopper>
https://codesandbox.io/s/combobox-demo-material-ui-forked-v5-8-4-g0pyhg?file=/demo.tsx

Markers clustering in #react-native-mapbox-gl/maps

I am using #react-native-mapbox-gl/maps and I want to implement clustering for markers. I couldn't find any solution for my implementation. Attach image will show that two markers should be combined but they are not.
Below I am pasting my code:
<MapboxGL.MapView
showUserLocatin={true}
zoomLevel={10}
zoomEnabled={zoomEnabled}
pitchEnabled={true}
onPress={onMapPress}
onRegionIsChanging={onRegionIsChanging}
surfaceView={true}
rotateEnabled={rotateEnabled}
compassEnabled={false}
showUserLocation={false}
userTrackingMode={MapboxGL.UserTrackingModes.None}
scrollEnabled={scrollEnabled}
styleURL={styleURL}
centerCoordinate={getFocusPoint() || getStartingPoint()}
ref={(c) => (_map = c)}
onRegionDidChange={onRegionChange}
style={style}
cluster
>
{renderLines()}
<MapboxGL.SymbolLayer
id={'abc'}
sourceID={MapboxGL.StyleSource.DefaultSourceID}
/>
<MapboxGL.Camera
zoomLevel={zoom}
centerCoordinate={getFocusPoint() || getStartingPoint()}
/>
{(simplePlaceData?.length > 0 || places?.length > 0) && renderMarkers()}
</MapboxGL.MapView>
Below is our renderMarkers function( basically I am displaying any RN component like image/icon inside MapboxGL.PointAnnotation):
const renderMarkers = () => {
if (simplePlaceData)
return simplePlaceData?.map((_place) => {
const {lat, lng, id} = _place
const latVal = parseFloat(lat)
const lngVal = parseFloat(lng)
if (!lat || !lng || isNaN(latVal) || isNaN(lngVal)) return null
return (
<MapboxGL.PointAnnotation
key={`${id}`}
id={`${id}`}
title={`${lat}-${lng}`}
coordinate={[parseFloat(lng), parseFloat(lat)]}>
<Col style={styles.mapMarkers}>
<Icon
name={'map-marker'}
family={'materialCommunity'}
color={Colors.linkBlue}
size={31}
/>
</Col>
</MapboxGL.PointAnnotation>
)
})
else
return places?.length > 0 && places.map(_place => {
const {lat, lng, id, image, name} = _place.trip_place.place
const isSelected = (getFocusPoint() || getStartingPoint())?.first() == lng &&
(getFocusPoint() || getStartingPoint())?.last() == lat
if (Platform.OS === 'ios') {
return (
<MapboxGL.PointAnnotation
key={`${id}`}
id={`${id}`}
title={name}
coordinate={[parseFloat(lng), parseFloat(lat)]}
>
<MapMarker
image={{uri: image}}
imageSize={isSelected ? 41 : 31}
style={isSelected ? styles.mapMarkersSelected : styles.mapMarkers}
onPress={() => selectPlace(_place.trip_place.place, true)}
/>
</MapboxGL.PointAnnotation>
)
} else {
return (
<MapboxGL.MarkerView
id={`${id}`}
key={`${id}`}
coordinate={[parseFloat(lng), parseFloat(lat)]}
title={name}
>
<View style={isSelected ? styles.mapMarkerContainerSelected : styles.mapMarkerContainer}>
<MapMarker
image={{uri: image}}
imageSize={isSelected ? 41 : 31}
style={isSelected ? styles.mapMarkersSelected : styles.mapMarkers}
onPress={() => selectPlace(_place.trip_place.place, true)}
/>
</View>
</MapboxGL.MarkerView>
)
}
})
}
Is there any solution to to apply for MapboxGL.PointAnnotation to show markers as a combined cluster with number of items inside? Or there is anothe component of MapboxGL which I can use to achieve this functionality?
Thanks
So from my experience with React Native Mapbox GL, you can't use point annotations for clustering. You'll have to use icons. One rule you have to keep in mind for this to work is that your markers have to be GEO JSON features collection. Checkout the link below if you don't know what that is.
https://enterprise.arcgis.com/en/geoevent/latest/ingest/GUID-F489B3D2-74DB-4EA2-8A4E-330628193843-web.png
Once you have your feature collection, you feed it into the Shapsource and clusters should start showing up.
<MapboxGL.ShapeSource
ref={shapeSource}
shape={{ type: 'FeatureCollection', features: [...''] }}
id="symbolLocationSource"
hitbox={{ width: 18, height: 18 }}
onPress={async point => {
if (point.features[0].properties.cluster) {
const collection = await shapeSource.current.getClusterLeaves(
point.features[0],
point.features[0].properties.point_count,
0,
)
// Do what you want if the user clicks the cluster
console.log(collection)
} else {
// Do what you want if the user clicks individual marker
console.log(point.features[0])
}
}}
clusterRadius={50}
clusterMaxZoom={14}
cluster
>
In order to get individual pictures for markers to show up once you zoom in; You'll need to get the image from the individual marker. So if you have a feature collection, each feature should have an image, you could either use an image stored in your project folder and replace the iconImage property in the symbol. Or if your feature has a link to an image, you could use the property in the feature like so:
iconImage: ['get', '___ whatever name you gave the link___'],
<MapboxGL.SymbolLayer
id="singlePoint"
filter={['!', ['has', 'point_count']]}
style={{
iconImage: ['get', '___ whatever name you gave the link___'],
iconSize: 0.3,
iconHaloColor: 'black',
iconHaloWidth: 10,
iconColor: 'white',
iconHaloColor: 'black',
iconHaloWidth: 400,
iconAllowOverlap: true,
}}
/>
in order to get that to show up you need mapbox images
<MapboxGL.Images
images={images}
onImageMissing={async url => {
setImages({ ...images, [url]: { uri: await getImage(url) } })
}}
/>
So that get request we did with the link, will call the mapbox images. Just make sure you have an images, and setImages in your state. This will then allow you to show the current image of your point annotation. Only problem is that it's hard to edit, so you can't just make them appear as circles unless they're cropped that way.
<MapboxGL.MapView
style={styles.map}
ref={mapRef}
styleURL="___ url___"
zoomEnabled
>
<MapboxGL.Camera
animationDuration={250}
ref={ref => (this.camera = ref)}
minZoomLevel={5}
zoomLevel={6}
maxZoomLevel={20}
animationMode="flyTo"
centerCoordinate={currrentLocation}
Level={stateZoomLevel}
/>
<MapboxGL.Images
images={images}
onImageMissing={async url => {
setImages({ ...images, [url]: { uri: await getImage(url) } })
}}
/>
{/* Cluster Individual Drop View */}
<MapboxGL.ShapeSource
ref={shapeSource}
shape={{ type: 'FeatureCollection', features: [...''] }}
id="symbolLocationSource"
hitbox={{ width: 18, height: 18 }}
onPress={async point => {
if (point.features[0].properties.cluster) {
const collection = await shapeSource.current.getClusterLeaves(
point.features[0],
point.features[0].properties.point_count,
0,
)
// Do what you want if the user clicks the cluster
console.log(collection)
} else {
// Do what you want if the user clicks individual marker
console.log(point.features[0])
}
}}
clusterRadius={50}
clusterMaxZoom={14}
cluster
>
<MapboxGL.SymbolLayer
id="pointCount"
style={layerStyles.clusterCount}
/>
<MapboxGL.UserLocation
visible
onUpdate={location => {
setCurrentLocation({
latitude: location.coords.latitude,
longitude: location.coords.longitude,
})
}}
/>
<MapboxGL.CircleLayer
id="clusteredPoints"
belowLayerID="pointCount"
filter={['has', 'point_count']}
style={{
circlePitchAlignment: 'map',
circleColor: '#A59ADD',
circleRadius: [
'step',
['get', 'point_count'],
20,
100,
25,
250,
30,
750,
40,
],
circleOpacity: 0.84,
circleStrokeWidth: 0,
circleStrokeColor: 'blue',
}}
/>
<MapboxGL.SymbolLayer
id="singlePoint"
filter={['!', ['has', 'point_count']]}
style={{
iconImage: ['get', '__image name___'],
iconSize: 0.3,
iconHaloColor: 'black',
iconHaloWidth: 10,
iconColor: 'white',
iconHaloColor: 'black',
iconHaloWidth: 400,
iconAllowOverlap: true,
}}
/>
</MapboxGL.ShapeSource>
</MapboxGL.MapView>
const layerStyles = {
singlePoint: {
circleColor: 'green',
circleOpacity: 0.84,
circleStrokeWidth: 2,
circleStrokeColor: 'white',
circleRadius: 5,
circlePitchAlignment: 'map',
},
clusteredPoints: {},
clusterCount: {
textField: '{point_count}',
textSize: 12,
textPitchAlignment: 'map',
},
}
If this helped upvote!

Styling react-select v2 with material-ui - Replace Input component

I'm having an issue with replacing the Input component for react-select v2 with the Input component from Material UI.
I've made an attempt so far in the codesandbox below, but unable to invoke the filtering upon typing into the Input?
https://codesandbox.io/s/jjjwoj3yz9
Also, any feedback on the Option replacement implementation would be appreciated. Am I going about it the right way with grabbing the text of the clicked option and search for the Option object from my options list to pass to the selectOption function?
Much appreciated,
Eric
V1
refer the documentation from here : https://material-ui.com/demos/autocomplete/
it provides clear documentation about how to use react-select with material-ui
here is a working example for your question: https://codesandbox.io/s/p9jpl9l827
as you can see material-ui Input component can take react-select as inputComponent.
V2
It's almost same as the previous approach :
implement the Input component:
<div className={classes.root}>
<Input
fullWidth
inputComponent={SelectWrapped}
value={this.state.value}
onChange={this.handleChange}
placeholder="Search your color"
id="react-select-single"
inputProps={{
options: colourOptions
}}
/>
</div>
and then SelectWrapped component implementation should be:
function SelectWrapped(props) {
const { classes, ...other } = props;
return (
<Select
components={{
Option: Option,
DropdownIndicator: ArrowDropDownIcon
}}
styles={customStyles}
isClearable={true}
{...other}
/>
);
}
and I overrides the component Option and DropdownIndicator to make it more material and added customStyles also:
const customStyles = {
control: () => ({
display: "flex",
alignItems: "center",
border: 0,
height: "auto",
background: "transparent",
"&:hover": {
boxShadow: "none"
}
}),
menu: () => ({
backgroundColor: "white",
boxShadow: "1px 2px 6px #888888", // should be changed as material-ui
position: "absolute",
left: 0,
top: `calc(100% + 1px)`,
width: "100%",
zIndex: 2,
maxHeight: ITEM_HEIGHT * 4.5
}),
menuList: () => ({
maxHeight: ITEM_HEIGHT * 4.5,
overflowY: "auto"
})
};
and Option:
class Option extends React.Component {
handleClick = event => {
this.props.selectOption(this.props.data, event);
};
render() {
const { children, isFocused, isSelected, onFocus } = this.props;
console.log(this.props);
return (
<MenuItem
onFocus={onFocus}
selected={isFocused}
onClick={this.handleClick}
component="div"
style={{
fontWeight: isSelected ? 500 : 400
}}
>
{children}
</MenuItem>
);
}
}
please find the example from here: https://codesandbox.io/s/7k82j5j1qx
refer the documentation from react select and you can add more changes if you wish.
hope these will help you.

Full screen background image in React Native app

I'm trying to set a full background image on my login view.
I found that question here in Stackoverflow: What's the best way to add a full screen background image in React Native
So I did it like there, but it didn't work:
var login = React.createClass({
render: function() {
return (
<View style={ styles.container }>
<Image source={require('../images/login_background.png')} style={styles.backgroundImage} />
<View style={ styles.loginForm }>
<Text>TEST</Text>
</View>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
},
backgroundImage: {
flex: 1,
resizeMode: 'cover', // or 'stretch'
},
loginForm: {
},
});
I don't know what I'm doing wrong. Any help would be appreciated.
Edit: Here is the app, in case you guys want to take it a look -> Full size background image example on rnplay.org. I don't know how to do it editable :/
Thanks :)
You should use ImageBackground component. See React Native Docs
<ImageBackground source={...} style={{width: '100%', height: '100%'}}>
<Text>Inside</Text>
</ImageBackground>
Try either of these two methods:
The first is similar to yours except you have position: 'absolute' on your login form:
var styles = StyleSheet.create({
container: {
flex: 1,
},
backgroundImage: {
flex: 1,
resizeMode: 'cover', // or 'stretch'
},
loginForm: {
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0
},
});
The second method involves using the ImageView as a container:
render: function() {
return (
<View style={ styles.container }>
<Image source={require('../images/login_background.png')} style={styles.backgroundImage}>
<View style={ styles.loginForm }>
<Text>TEST</Text>
</View>
</Image>
</View>
);
}
I was doing a silly mistake...
Text component has a white background, and I thought the problem was with the Image and stuff...
So, the solution is to wrap the info inside the Image tag, as #Cherniv and #kamikazeOvrld said, but also set transparent background to the component inside it.
Here is the fully working example:
Code:
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
Image,
StatusBarIOS
} = React;
StatusBarIOS.setHidden(true);
var SampleApp = React.createClass({
render: function() {
return (
<View style={ styles.container }>
<Image source={{uri: 'http://puu.sh/mJ1ZP/6f167c37e5.png'}} style={styles.backgroundImage} >
<View style={ styles.loginForm }>
<Text style={ styles.text }>Some text</Text>
</View>
</Image>
</View>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
},
backgroundImage: {
flex: 1,
resizeMode: 'cover', // or 'stretch',
justifyContent: 'center',
},
loginForm: {
backgroundColor: 'transparent',
alignItems: 'center',
},
text: {
fontSize: 30,
fontWeight: 'bold',
}
});
AppRegistry.registerComponent('SampleApp', () => SampleApp);
Also in rnplay.org
I hope it helps someone like me, when you are writing code all day, your brain doesn't work as well as you'd like!
Thanks.
Umesh, the answer to your problem is already stated clearly.
The <Image /> component does not contain any children component. What you need to do is to use the <ImageBackground /> component as this will allow you embed other components inside it making them as children. So in your case you should do something like this
<ImageBackground>
<Text>Write your text and some other stuffs here...</Text>
</ImageBackground>
Note: Don't forget to add flex: 1 or width.
I hope my answer was clear enough.
Thanks.
<View style={styles.imageCancel}>
<TouchableOpacity onPress={() => { this.setModalVisible(!this.state.visible) }}>
<Text style={styles.textCancel} >Close</Text>
</TouchableOpacity>
</View>
const styles = StyleSheet.create({
imageCancel: {
height: 'auto',
width: 'auto',
justifyContent:'center',
backgroundColor: '#000000',
alignItems: 'flex-end',
},
textCancel: {
paddingTop:25,
paddingRight:25,
fontSize : 18,
color : "#ffffff",
height: 50,
},
}};