score:-3
to have multiple inline styles in react.
<div onclick={eletemplate} style={{'width': '50%', textalign: 'center'}}/>
score:0
i have built an module for this if you want to add styles based on a condition like this:
multiplestyles(styles.icon, { [styles.iconred]: true })
score:1
so basically i'm looking at this in the wrong way. from what i see, this is not a react specific question, more of a javascript question in how do i combine two javascript objects together (without clobbering similarly named properties).
in this stackoverflow answer it explains it. how can i merge properties of two javascript objects dynamically?
in jquery i can use the extend method.
score:1
to expand on what @pythonisgreat said, i create a global function that will do it for me:
var css = function(){
var args = $.merge([true, {}], array.prototype.splice.call(arguments, 0));
return $.extend.apply(null, args);
}
this deeply extends the objects into a new object and allows for a variable number of objects as parameters. this allows you to do something like this:
return(
<div style={css(styles.base, styles.first, styles.second,...)} ></div>
);
var styles = {
base:{
//whatever
},
first:{
//whatever
},
second:{
//whatever
}
}
score:1
to take this one even further, you could create a classnames-like helper function:
const stylerules = (...rules) => {
return rules.filter(boolean).reduce((result, rule) => {
return { ...result, ...rule };
}, {});
};
and then use it conditionally in your components:
<div style={
stylerules(
divstyle,
(window.innerwidth >= 768) && divstylemd,
(window.innerwidth < 768) && divstylesm
)
}>hello world!</div>
score:1
ways of inline styling:
<view style={[styles.red, {fontsize: 25}]}>
<text>hello world</text>
</view>
<view style={[styles.red, styles.blue]}>
<text>hello world</text>
</view>
<view style={{fontsize:10,margintop:10}}>
<text>hello world</text>
</view>
score:2
for ones that looking this solution in react, if you want to use the spread operator inside style, you should use: babel-plugin-transform-object-rest-spread.
install it by npm module and configure your .babelrc as such:
{
"presets": ["env", "react"],
"plugins": ["transform-object-rest-spread"]
}
then you can use like...
const sizing = { width: 200, height: 200 }
<div
classname="dragon-avatar-image-background"
style={{ backgroundcolor: blue, ...sizing }}
/>
more info: https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread/
score:2
you can use compose
const styles = stylesheet.create({
divstyle :{
color: 'white',
backgroundimage: 'url(' + imgurl + ')',
webkittransition: 'all', // note the capital 'w' here
mstransition: 'all' // 'ms' is the only lowercase vendor prefix
},
divstyle2 :{fontsize: '18px'}
})
react.render(<div style={stylesheet.compose(styles.divstyle, styles.divstyle2)}>hello world!</div>, mountnode);
or
react.render(<div style={[styles.divstyle, styles.divstyle2]}>hello world!</div>, mountnode);
score:6
need to merge the properties in object. for example,
const boxstyle = {
width : "50px",
height : "50px"
};
const redbackground = {
...boxstyle,
background: "red",
};
const bluebackground = {
...boxstyle,
background: "blue",
}
<div style={redbackground}></div>
<div style={bluebackground}></div>
score:7
i've found that this works best for me. it overrides as expected.
return <view style={{...styles.local, ...styles.fromprops}} />
score:13
you can also combine classes with inline styling like this:
<view style={[classname, {paddingtop: 25}]}>
<text>some text</text>
</view>
score:20
actually, there is a formal way to combine and it is like below:
<view style={[style01, style02]} />
but, there is a small issue, if one of them is passed by the parent component and it was created by a combined formal way we have a big problem:
// the passing style02 from props: [parentstyle01, parentstyle02]
// now:
<view style={[style01, [parentstyle01, parentstyle02]]} />
and this last line causes to have ui bug, surly, react native cannot deal with a deep array inside an array. so i create my helper function:
import { stylesheet } from 'react-native';
const stylejoiner = (...arg) => stylesheet.flatten(arg);
by using my stylejoiner
anywhere you can combine any type of style and combine styles. even undefined
or other useless types don't cause to break the styling.
score:22
const style1 = {
backgroundcolor: "#2196f3",
}
const style2 = {
color: "white",
}
const somecomponent = () => {
return <div style={{ ...style1, ...style2 }}>this has 2 separate styles</div>
}
note the double curly brackets. the spread operator is your friend.
score:27
array notaion is the best way of combining styles in react native.
this shows how to combine 2 style objects,
<text style={[styles.base, styles.background]} >test </text>
this shows how to combine style object and property,
<text style={[styles.base, {color: 'red'}]} >test </text>
this will work on any react native application.
score:32
object.assign()
is an easy solution, but the (currently) top answer's usage of it — while just fine for making stateless components, will cause problems for the op's desired objective of merging two state
objects.
with two arguments, object.assign()
will actually mutate the first object in-place, affecting future instantiations.
ex:
consider two possible style configs for a box:
var styles = {
box: {backgroundcolor: 'yellow', height: '100px', width: '200px'},
boxa: {backgroundcolor: 'blue'},
};
so we want all our boxes to have default 'box' styles, but want to overwrite some with a different color:
// this will be yellow
<div style={styles.box}></div>
// this will be blue
<div style={object.assign(styles.box, styles.boxa)}></div>
// this should be yellow, but it's blue.
<div style={styles.box}></div>
once object.assign()
executes, the 'styles.box' object is changed for good.
the solution is to pass an empty object to object.assign()
. in so doing, you're telling the method to produce a new object with the objects you pass it. like so:
// this will be yellow
<div style={styles.box}></div>
// this will be blue
<div style={object.assign({}, styles.box, styles.boxa)}></div>
// a beautiful yellow
<div style={styles.box}></div>
this notion of objects mutating in-place is critical for react, and proper use of object.assign()
is really helpful for using libraries like redux.
score:48
unlike react native, we cannot pass array of styles in react, like
<view style={[style1, style2]} />
in react, we need to create the single object of styles before passing it to style property. like:
const header = (props) => {
let basestyle = {
color: 'red',
}
let enhancedstyle = {
fontsize: '38px'
}
return(
<h1 style={{...basestyle, ...enhancedstyle}}>{props.title}</h1>
);
}
we have used es6 spread operator to combine two styles. you can also use object.assign() as well for the same purpose.
this also works if you don't need to store your style in a var
<segment style={{...segmentstyle, ...{height:'100%'}}}>
your content
</segment>
score:63
you can do this with object.assign()
.
in your example, you would do:
reactdom.render(
<div style={object.assign(divstyle, divstyle2)}>
hello world!
</div>,
mountnode
);
that will merge the two styles. the second style will replace the first if there are matching properties.
as brandon noted, you should use object.assign({}, divstyle, divstyle2)
if you want to reuse divstyle
without the fontsize applied to it.
i like to use this to make components with default properties. for example, here's a little stateless component with a default margin-right
:
const divwithdefaults = ({ style, children, ...otherprops }) =>
<div style={object.assign({ marginright: "1.5em" }, style)} {...otherprops}>
{children}
</div>;
so we can render something like this:
<divwithdefaults>
some text.
</divwithdefaults>
<divwithdefaults classname="someclass" style={{ width: "50%" }}>
some more text.
</divwithdefaults>
<divwithdefaults id="someid" style={{ marginright: "10px", height: "20px" }}>
even more text.
</divwithdefaults>
which will give us the result:
<div style="margin-right:1.5em;">some text.</div>
<div style="margin-right:1.5em;width50%;" class="someclass">some more text.</div>
<div style="margin-right:10px;height:20px;" id="someid">even more text.</div>
score:339
you can use the spread operator:
<button style={{...styles.panel.button,...styles.panel.backbutton}}>back</button
score:542
if you're using react native, you can use the array notation:
<view style={[styles.base, styles.background]} />
check out my detailed blog post about this.
Source: stackoverflow.com
Related Query
- How to combine multiple inline style objects?
- ReactJs - Combine multiple style objects immutably
- How to combine inline style and external import const style in JSX React
- Inline CSS in React - how to style multiple li elements
- React how to inline style different objects in one element
- reactjs - how to set inline style of backgroundcolor?
- React native: How to combine external and inline styles?
- React useReducer: How to combine multiple reducers?
- How to combine and use multiple Next.js plugins
- how to add inline style width:calc(100% / var) in reactjs?
- React: How to combine each multiple styles marked in Material-UI
- How to set -webkit-overflow-scrolling inline style on react component
- How to Lazy load the background image inside the inline style property (React)?
- How to add multiple style attributes to a react element?
- How to reuse the same style rule with multiple selectors
- How redux work when multiple components use parts of complex objects for it's source
- How to add !important into React inline CSS style
- How to efficiently style a table inline in react
- How can I combine multiple combineReducers functions in Redux using something like immutable.js
- How to map API with multiple objects [Spree API V2 & ReactJS]
- How to combine multiple classNames in React?
- How To Apply Inline Style and className to Same Element
- React Native Inline style for multiple Text in single Text With Touch effect
- How to inline multiple SVGs with React using Webpack?
- Can't figure out how to style rc-slider (React Component Slider) via inline styling
- How can I combine multiple loaders (CSS, LESS, ttf, etc) in NextJS config file?
- How to count multiple objects inside nested array sequentially in react js
- how to add multiple objects in reactjs?
- React - multiple properties on an inline style for filter
- How do you add multiple browser specific values into a CSS style in React?
More Query from same tag
- Reactjs send data through pages and components
- How to export components like Row, Col from antd library in my custom library without any change?
- How to create shared-singleton components across all the platform?
- getting an error like Too many re-renders. React limits the number of renders to prevent an infinite loop
- setState not being executed maybe
- How can I find if firebaseAuthIsReady with v3.0.0?
- Q: How to set up a mix of public and protected routes? (React Router)
- How to iterate over an array of object and show only the latest value in a child component?
- Destructuring useContext data
- React-native insert a value from render array to new array
- Firebase PWA won't authenticate offline users in mobile browsers (works fine on desktop)
- Is it possible to use Graphql query with React Class component?
- Unable to read props data object in getInitialState and ComponentDidMount in the child component in reactjs
- Chane Image on Click in React Native
- Unicode FontAwesome on Sass in ReactJS
- Javascript - extract data from object
- How to enable polygon (geofence) editing enable,on clicking polygon itself, without clicking on Edit button
- How to get data from firebase cloud firestore in react
- React.js: How can I show the birthdate field till date in React?
- @testing-library/react-hooks calls setTimeout two times
- My map gives me Cannot read properties of undefined (reading 'map')
- Material-ui v5 - where is DataGrid component? ( How to install DataGrid component in material-ui v5 In react?)
- How to update whole Uint8Array value using useState in React Hook?
- How to Unit test the rendering of a child component in the parent component using react testing library?
- What is the benefit of re-exporting modules?
- Trying to filter array of object based on returned values
- Laravel 5.5 React
- How react functional component can use object variable which declared behind the usage? (include example)
- How can I draw red horizontal line in React
- How to test a React Snackbar did not appear with Cypress