How to mock NextJS next/future/image in Storybook - next.js

How can I mock next/future/image component from NextJS in Storybook?

Mock with support of fill property from v12.2.4
// .storybook/preview.js
import * as NextFutureImage from "next/future/image";
Object.defineProperty(NextFutureImage, "default", {
configurable: true,
value: (props) => {
const { fill, style, ...restProps } = props;
return (
<img
{...restProps}
style={
fill
? {
position: "absolute",
height: "100%",
width: "100%",
inset: 0,
...style
}
: style
}
/>
);
},
});

Related

crop image with react - customize react-easy-crop styling

I'm trying to make a very simple react component that would crop images with react-easy-crop. Apparently it is possible to customize the style of react-easy-crop module with style prop that takes 3 objects: containerStyle, mediaStyle and cropAreaStyle.
This is the default layout:
I want to expand cropArea to full width of its container and to fit media in it by height (so that we don't see the part of the original image outside of cropArea) but can't figure out how to do it. The cropAreaStyle object doesn't seem to affect width or height since it is calculated and injected in the module file (even after setting disableAutomaticStylesInjection to true).
import React from 'react'
import ReactDOM from 'react-dom'
import Cropper from 'react-easy-crop'
import './styles.css'
class App extends React.Component {
state = {
imageSrc:
'https://img.huffingtonpost.com/asset/5ab4d4ac2000007d06eb2c56.jpeg?cache=sih0jwle4e&ops=1910_1000',
crop: { x: 0, y: 0 },
zoom: 1,
aspect: 1 / 1,
style: { containerStyle: { position: "absolute", top: "0", width: "calc(100% - 2px)", height: window.innerWidth, overflow: "hidden", border: "1px solid black" },
mediaStyle: { height: "100%", display: "block" },
cropAreaStyle: {position: "absolute", top: "0", border: "1px solid black", width: "100%", height: "100%" }}
}
onCropChange = (crop) => {
this.setState({ crop })
}
onCropComplete = (croppedArea, croppedAreaPixels) => {
console.log(croppedArea, croppedAreaPixels)
}
onZoomChange = (zoom) => {
this.setState({ zoom })
}
render() {
return (
<div className="App">
<div className="crop-container">
<Cropper
image={this.state.imageSrc}
crop={this.state.crop}
zoom={this.state.zoom}
aspect={this.state.aspect}
onCropChange={this.onCropChange}
onCropComplete={this.onCropComplete}
onZoomChange={this.onZoomChange}
style={this.state.style}
disableAutomaticStylesInjection={true}
/>
</div>
</div>
)
}
}
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)
This is what I'm trying to achieve:
The black square is cropArea that I can't resize...
I want cropArea to remain square.
Is there an easy way to do this, without changing the module file?
The solution with another module is acceptable also
Thanks in advance
I tried to use the object cropAreaStyle but it's not working, instead use the prop cropSize and don't pass the prop aspect.
In order to get the height of the media pass the prop onMediaLoaded:
onMediaLoad = (mediaSize) => {
this.setState({
cropHeight: mediaSize.height,
});
};
App.js
import React from 'react';
import ReactDOM from 'react-dom';
import Cropper from 'react-easy-crop';
import './style.css';
class App extends React.Component {
state = {
imageSrc:
'https://img.huffingtonpost.com/asset/5ab4d4ac2000007d06eb2c56.jpeg?cache=sih0jwle4e&ops=1910_1000',
crop: { x: 0, y: 0 },
zoom: 1,
cropHeight: 0,
};
onCropChange = (crop) => {
this.setState({ crop });
};
onCropComplete = (croppedArea, croppedAreaPixels) => {
console.log(croppedArea, croppedAreaPixels);
};
onZoomChange = (zoom) => {
this.setState({ zoom });
};
onMediaLoad = (mediaSize) => {
this.setState({
cropHeight: mediaSize.height,
});
};
render() {
const cropSize = {
height: `${this.state.cropHeight}px`,
width: '100%',
};
return (
<div className="App">
<div className="crop-container">
<Cropper
image={this.state.imageSrc}
crop={this.state.crop}
zoom={this.state.zoom}
onCropChange={this.onCropChange}
onCropComplete={this.onCropComplete}
onZoomChange={this.onZoomChange}
onMediaLoaded={this.onMediaLoad}
cropSize={cropSize}
/>
</div>
</div>
);
}
}
export default App;
Demo: https://stackblitz.com/edit/react-4zmgud
It seems that what you need is the objectFit property set to vertical-cover.
See this demo: https://codesandbox.io/s/crazy-liskov-04u7m0

How to dispatch Redux action without "onClick"?

For the below line of code, how can I dispatch notificationsStateUpdate without onClick? I want this action to be dispatched if notificationClicked is true, so I currently have a ternary expression set up.
However, I can't seem to get the syntax to work. Is it possible to dispatch in this scenario?
{notificationClicked ?
<NotificationList
notifications={newNotifications} />
dispatch(notificationsStateUpdate({newNotifications}))
: null}
Full code for context
import React, { useState, useEffect, useRef } from 'react';
import { useSelector, useDispatch, connect } from 'react-redux';
import _ from 'lodash';
import {makeStyles, useTheme} from '#material-ui/core/styles';
import usePrevious from '../hooks/usePrevious';
import NotificationList from './NotificationList';
import { notificationsStateUpdate } from '../actions';
export default function Notifications(props) {
const [newNotifications, setNewNotifications] = useState([]);
const users = useSelector(state => state.users);
const notificationClicked = useSelector(state => state.notificationClicked)
const prevUsers = usePrevious(users);
const dispatch = useDispatch();
console.log('inside', users);
const isEqual = _.isEqual(prevUsers, users);
const timestamp = !isEqual ? new Date().getTime() : new Date("1991-09-24").getTime();
useEffect(() => {
const notifications = [];
console.log('users', users);
users.forEach((user) => {
if (user.uid === props.uid && user.posts) {
user.posts.forEach((postContent) => {
const likes = postContent.like ? Object.values(postContent.like) : null
const comments = postContent.comments_text ? Object.values(postContent.comments_text) : null
if (likes){
let filtererdLikes = likes.filter(post => {
return post.like_notification === false
})
notifications.push(filtererdLikes)
}
if (comments){
let letfilteredComments = comments.filter(post => {
return post.comment_notification === false
})
notifications.push(letfilteredComments)
}
})
}
});
const notificationsDataClean = notifications.flat(Infinity)
setNewNotifications(notificationsDataClean);
}, [timestamp]);
const useStyles = makeStyles((theme) => ({
body: {
margin: '25',
background: '#3f51b5'
},
iconButton: {
position: 'relative',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
width: 50,
height: 50,
color: '#333333',
background: '#dddddd',
border: 'none',
outline: 'none',
borderRadius: '50%',
'&:hover': {
cursor: 'pointer'
},
'&:active': {
background: '#cccccc'
}
},
iconButton__badge: {
position: 'absolute',
top: -10,
right: -10,
width: 25,
height: 25,
background: 'red',
color: '#ffffff',
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
borderRadius: '50%'
}
}
));
const classes = useStyles();
const theme = useTheme();
return (
<div>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Icon Button Notification Badge</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
</head>
<body className={classes.body}>
<button type="button" className={classes.iconButton}>
<span class="material-icons">notifications</span>
<span className={classes.iconButton__badge}>{newNotifications.length}</span>
</button>
</body>
{notificationClicked ? <NotificationList notifications={newNotifications} /> dispatch(notificationsStateUpdate({newNotifications})) : null}
</div>
);
}
If I am understanding correctly, this should work
<NotificationList
notificationClicked, // pass in as prop instead of a ternary
notifications={newNotifications} />
then call your dispatch in useEffect in NotificationList
<NotificationList>
/////
useEffect =(() => {
//Whatever else
if (notificationClicked) {
dispatch(notificationsStateUpdate({newNotifications}))
}
},[notificationClicked])

Change background-color of component depending on where i call it

I've got a problem I can't seem to solve.
I use a component several times in my app but I'd like the background to be different.
I've declared an empty state for the moment, which I'm using in background-color but I can't define the color the component will have. How can I do this?
Thanks for your help
Here is a little piece of my code :
class Gallery extends React.Component {
constructor(props) {
super(props)
this.state = {
activeGal: [],
width: 1920,
teamGal: {},
isOpen: false,
photoIndex: 0,
bgColor: ''
}
}
render() {
const {activeGal, width, teamGal, isOpen, photoIndex, bgColor} = this.state
.gallery {
background-color: ${bgColor};
padding-bottom: 55px;
}
The easiest (and not recommended) way is to use the style prop:
class Gallery extends React.Component {
render() {
const { backgroundColor } = this.props;
return <div style={{ width: "100%", height: "100%", backgroundColor }} />;
}
}
const App = () => {
return (
<div style={{ height: "50vh", width: "50vw" }}>
<Gallery backgroundColor="blue" />
</div>
);
};
More popular solutions are using CSS-in-JS (like styled-components) or CSS variables (See CSS Variables for React Devs).

React: make boxes same size even with different content

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;
}

Can I make dynamic styles in React Native?

Say I have a component with a render like this:
<View style={jewelStyle}></View>
Where jewelStyle =
{
borderRadius: 10,
backgroundColor: '#FFEFCC',
width: 20,
height: 20,
},
How could I make the background colour dynamic and randomly assigned? I've tried
{
borderRadius: 10,
backgroundColor: getRandomColor(),
width: 20,
height: 20,
},
But this makes all instances of View have the same colour, I want each one to be unique.
Any tips?
I usually do something along the lines of:
<View style={this.jewelStyle()} />
...
jewelStyle = function(options) {
return {
borderRadius: 12,
background: randomColor(),
}
}
Every time View is rendered, a new style object will be instantiated with a random color associated with it. Of course, this means that the colors will change every time the component is re-rendered, which is perhaps not what you want. Instead, you could do something like this:
var myColor = randomColor()
<View style={jewelStyle(myColor)} />
...
jewelStyle = function(myColor) {
return {
borderRadius: 10,
background: myColor,
}
}
Yes you can and actually, you should use StyleSheet.create to create your styles.
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
class Header extends Component {
constructor(props){
super(props);
}
render() {
const { title, style } = this.props;
const { header, text } = defaultStyle;
const combineStyles = StyleSheet.flatten([header, style]);
return (
<View style={ combineStyles }>
<Text style={ text }>
{ title }
</Text>
</View>
);
}
}
const defaultStyle = StyleSheet.create({
header: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
height: 60,
paddingTop: 15,
shadowColor: '#000',
shadowOffset: { width: 0, height: 3 },
shadowOpacity: 0.4,
elevation: 2,
position: 'relative'
},
text: {
color: '#0d4220',
fontSize: 16
}
});
export default Header;
And then:
<Header title="HOME" style={ {backgroundColor: '#10f1f0'} } />
If you still want to take advantage of StyleSheet.create and also have dynamic styles, try this out:
const Circle = ({initial}) => {
const initial = user.pending ? user.email[0] : user.firstName[0];
const colorStyles = {
backgroundColor: randomColor()
};
return (
<View style={[styles.circle, colorStyles]}>
<Text style={styles.text}>{initial.toUpperCase()}</Text>
</View>
);
};
const styles = StyleSheet.create({
circle: {
height: 40,
width: 40,
borderRadius: 30,
overflow: 'hidden'
},
text: {
fontSize: 12,
lineHeight: 40,
color: '#fff',
textAlign: 'center'
}
});
Notice how the style property of the View is set as an array that combines your stylesheet with your dynamic styles.
The easiest is mine:
<TextInput
style={[
styles.default,
this.props.singleSourceOfTruth ?
{ backgroundColor: 'black' }
: { backgroundColor: 'white' }
]}/>
Had some issue syntactically.
This worked for me
<Text style={[styles.textStyle,{color: 'red'}]}> Hello </Text>
const styles = StyleSheet.create({
textStyle :{
textAlign: 'center',
fontFamily: 'Arial',
fontSize: 16
}
});
You'll want something like this:
var RandomBgApp = React.createClass({
render: function() {
var getRandomColor = function() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
var rows = [
{ name: 'row 1'},
{ name: 'row 2'},
{ name: 'row 3'}
];
var rowNodes = rows.map(function(row) {
return <Text style={{backgroundColor:getRandomColor()}}>{row.name}</Text>
});
return (
<View>
{rowNodes}
</View>
);
}
});
In this example I take the rows array, containing the data for the rows in the component, and map it into an array of Text components. I use inline styles to call the getRandomColor function every time I create a new Text component.
The issue with your code is that you define the style once and therefore getRandomColor only gets called once - when you define the style.
I know this is extremely late, but for anyone still wondering here's an easy solution.
You could just make an array for the styles :
this.state ={
color: "#fff"
}
style={[
styles.jewelstyle, {
backgroundColor: this.state.BGcolor
}
The second will override any original background color as stated in the stylesheet. Then have a function that changes the color:
generateNewColor(){
var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
this.setState({BGcolor: randomColor})
}
This will generate a random hex color. Then just call that function whenever and bam, new background color.
Actually, you can write your StyleSheet.create object as a key with function value, it works properly but it has a type issue in TypeScript:
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const SomeComponent = ({ bgColor }) => (
<View style={styles.wrapper(bgColor)}>
<Text style={styles.text}>3333</Text>
</View>
);
const styles = StyleSheet.create({
wrapper: color => ({
flex: 1,
backgroundColor: color,
}),
text: {
color: 'red',
},
});
import React, { useContext, useMemo } from 'react';
import { Text, StyleSheet, View } from 'react-native';
import colors from '../utils/colors';
import ThemeContext from './../contexts/ThemeContext';
export default (props) => {
const { theme } = useContext(ThemeContext);
// Constructing styles for current theme
const styles = useMemo(() => createStyles(theme), [theme]);
return (
<View style={styles.container}>
<Text style={styles.label}>{label}</Text>
</View>
);
};
const createStyles = (theme: AppTheme) =>
StyleSheet.create({
container: { width: '100%', position: 'relative', backgroundColor: colors[theme].background },
label: {
fontSize: 13,
fontWeight: 'bold',
},
});
colors.ts
export type AppTheme = 'dark' | 'light';
const light: Colors = {
background: '#FFFFFF',
onBackground: '#333333',
gray: '#999999',
grayLight: '#DDDDDD',
red: 'red',
};
const dark: Colors = {
background: '#333333',
onBackground: '#EEEEEE',
gray: '#999999',
grayLight: '#DDDDDD',
red: 'red',
};
const colors = {
dark,
light,
primary: '#2E9767',
secondary: '#F6D130',
};
export default colors;
Using object spread operator "..." worked for me:
<View style={{...jewelStyle, ...{'backgroundColor': getRandomColor()}}}></View>
Yes, you can make dynamic styles. You can pass values from Components.
First create StyleSheetFactory.js
import { StyleSheet } from "react-native";
export default class StyleSheetFactory {
static getSheet(backColor) {
return StyleSheet.create({
jewelStyle: {
borderRadius: 10,
backgroundColor: backColor,
width: 20,
height: 20,
}
})
}
}
then use it in your component following way
import React from "react";
import { View } from "react-native";
import StyleSheetFactory from './StyleSheetFactory'
class Main extends React.Component {
getRandomColor = () => {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
render() {
return (
<View>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
</View>
);
}
}
<View
style={[styles.categoryItem,{marginTop: index <= numOfColumns-1 ? 10 : 0 }]}
>
I know there are several answers, but i think the best and most simple is using a state "To change" is the state purpose.
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
style: {
backgroundColor: "white"
}
};
}
onPress = function() {
this.setState({style: {backgroundColor: "red"}});
}
render() {
return (
...
<View style={this.state.style}></View>
...
)
}
}
You can bind state value directly to style object. Here is an example:
class Timer extends Component{
constructor(props){
super(props);
this.state = {timer: 0, color: '#FF0000'};
setInterval(() => {
this.setState({timer: this.state.timer + 1, color: this.state.timer % 2 == 0 ? '#FF0000' : '#0000FF'});
}, 1000);
}
render(){
return (
<View>
<Text>Timer:</Text>
<Text style={{backgroundColor: this.state.color}}>{this.state.timer}</Text>
</View>
);
}
}
If you are using a screen with filters for example, and you want to set the background of the filter regarding if it was selected or not, you can do:
<TouchableOpacity style={this.props.venueFilters.includes('Bar')?styles.filterBtnActive:styles.filterBtn} onPress={()=>this.setFilter('Bar')}>
<Text numberOfLines={1}>
Bar
</Text>
</TouchableOpacity>
On which set filter is:
setVenueFilter(filter){
var filters = this.props.venueFilters;
filters.push(filter);
console.log(filters.includes('Bar'), "Inclui Bar");
this.setState(previousState => {
return { updateFilter: !previousState.updateFilter };
});
this.props.setVenueFilter(filters);
}
PS: the function this.props.setVenueFilter(filters) is a redux action, and this.props.venueFilters is a redux state.
You can do something like this.
In your component:
const getRandomColor = () => {
// you can use your component props here.
}
<View style={[styles.jewelStyle, {backgroundColor: getRandomColor()}]} />
Create your style using stylesheet:
const styles = StyleSheet.create({
jewelStyle: {
backgroundColor: 'red',
},
});
If you are following the functional approach of React-Native, you can use a package called dynamic-styles that tries to solve exactly your problem.
// -- theme.js ------------------------------------------------------
// Initialization of a StyleSheet instance called 'styleSheet'
export const styleSheet = createStyleSheet({
theme: /* optional theme */
});
// -- MyComponent.js -----------------------------------------------
// Create dynamic stylesheet that has access
// to the previously specified theme and parameters
const useStyles = styleSheet.create(({theme, params}) => ({
root: /* Dynamic Styles */,
button: /* Dynamic Styles */,
text: /* Dynamic Styles */,
}));
const MyComponent = (props) => {
// Access dynamic styles using the created 'useStyles()' hook
// and specify the corresponding parameters
const { styles } = useStyles({ color: props.color, fontSize: 10 });
return (
<div className={styles.root}>
{/* */}
</div>
);
}
It basically allows you to create dynamic stylesheets
and link them to functional Components using the React hook pattern.
-> Codesandbox
In case someone needs to apply conditions
selectedMenuUI = function(value) {
if(value==this.state.selectedMenu){
return {
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 20,
paddingVertical: 10,
backgroundColor: 'rgba(255,255,255,0.3)',
borderRadius: 5
}
}
return {
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 20,
paddingVertical: 10
}
}
Here is what worked for me:
render() {
const { styleValue } = this.props;
const dynamicStyleUpdatedFromProps = {
height: styleValue,
width: styleValue,
borderRadius: styleValue,
}
return (
<View style={{ ...styles.staticStyleCreatedFromStyleSheet, ...dynamicStyleUpdatedFromProps }} />
);
}
For some reason, this was the only way that mine would update properly.
you can use styled-components for react native it will provide you dynamic styling just like emotion or styled-components for web.
For something relatively simple, you can use this approach:
StyleSheet.create({
item: props.selectedId === item.id ? {
backgroundColor: 'red',
}: null
});

Resources