score:126
If you prefer to use a class name, by all means use a class name.
className={completed ? 'text-strike' : null}
You may also find the classnames package helpful. With it, your code would look like this:
className={classNames({ 'text-strike': completed })}
There's no "correct" way to do conditional styling. Do whatever works best for you. For myself, I prefer to avoid inline styling and use classes in the manner just described.
POSTSCRIPT [06-AUG-2019]
Whilst it remains true that React is unopinionated about styling, these days I would recommend a CSS-in-JS solution; namely styled components or emotion. If you're new to React, stick to CSS classes or inline styles to begin with. But once you're comfortable with React I recommend adopting one of these libraries. I use them in every project.
score:0
The best way to handle styling is by using classes with set of css properties.
example:
<Component className={this.getColor()} />
getColor() {
let class = "badge m2";
class += this.state.count===0 ? "warning" : danger;
return class;
}
score:0
You can use somthing like this.
render () {
var btnClass = 'btn';
if (this.state.isPressed) btnClass += ' btn-pressed';
else if (this.state.isHovered) btnClass += ' btn-over';
return <button className={btnClass}>{this.props.label}</button>;
}
Or else, you can use classnames NPM package to make dynamic and conditional className props simpler to work with (especially more so than conditional string manipulation).
classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'
score:0
In case someone uses Typescript
(which does not except null
values for style) and wants to use react styling, I would suggest this hack:
<p
style={choiceStyle ? styles.choiceIsMade : styles.none}>
{question}
</p>
const styles = {
choiceIsMade: {...},
none: {}
}
score:0
Change Inline CSS Conditionally Based on Component State.
This is also the Correct way to handle conditional styling in React.
condition ? expressionIfTrue : expressionIfFalse;
example =>
{this.state.input.length > 15 ? inputStyle={border: '3px solid red'}: inputStyle }
This code means that if the character is more than 15 entered in the input field, then our input field's border will be red and the length of the border will be 3px.
score:3
I came across this question while trying to answer the same question. McCrohan's approach with the classes array & join is solid.
Through my experience, I have been working with a lot of legacy ruby code that is being converted to React and as we build the component(s) up I find myself reaching out for both existing css classes and inline styles.
example snippet inside a component:
// if failed, progress bar is red, otherwise green
<div
className={`progress-bar ${failed ? 'failed' : ''}`}
style={{ width: this.getPercentage() }}
/>
Again, I find myself reaching out to legacy css code, "packaging" it with the component and moving on.
So, I really feel that it is a bit in the air as to what is "best" as that label will vary greatly depending on your project.
score:3
style={{
whiteSpace: "unset",
wordBreak: "break-all",
backgroundColor: one.read == false && "#e1f4f3",
borderBottom:'0.8px solid #fefefe'
}}
score:3
If you want assign styles based on condition, its better you use a class name for styles. For this assignment, there are different ways. These are two of them.
1.
<div className={`another-class ${condition ? 'active' : ''}`} />
<div className={`another-class ${condition && 'active'}`} />
score:8
First, I agree with you as a matter of style - I would also (and do also) conditionally apply classes rather than inline styles. But you can use the same technique:
<div className={{completed ? "completed" : ""}}></div>
For more complex sets of state, accumulate an array of classes and apply them:
var classes = [];
if (completed) classes.push("completed");
if (foo) classes.push("foo");
if (someComplicatedCondition) classes.push("bar");
return <div className={{classes.join(" ")}}></div>;
score:11
Another way, using inline style and the spread operator
style={{
...completed ? { textDecoration: completed } : {}
}}
That way be useful in some situations where you want to add a bunch of properties at the same time base on the condition.
score:14
instead of this:
style={{
textDecoration: completed ? 'line-through' : 'none'
}}
you could try the following using short circuiting:
style={{
textDecoration: completed && 'line-through'
}}
https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb
key bit of information from the link:
Short circuiting means that in JavaScript when we are evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.
It's worth noting that this would return false if the first operand is false, so might have to consider how this would affect your style.
The other solutions might be more best practice, but thought it would be worth sharing.
score:14
inline style handling
style={{backgroundColor: selected ? 'red':'green'}}
using Css
in js
className={`section ${selected && 'section_selected'}`}
in css
.section {
display: flex;
align-items: center;
}
.section_selected{
background-color: whitesmoke;
border-width: 3px !important;
}
same can be done with Js stylesheets
score:85
If you need to conditionally apply inline styles (apply all or nothing) then this notation also works:
style={ someCondition ? { textAlign:'center', paddingTop: '50%'} : {}}
In case 'someCondition' not fulfilled then you pass empty object.
score:161
<div style={{ visibility: this.state.driverDetails.firstName != undefined? 'visible': 'hidden'}}></div>
Checkout the above code. That will do the trick.
Source: stackoverflow.com
Related Query
- Correct way to handle conditional styling in React
- React Redux correct way to handle error / success messages unique to each component
- React Hook : Correct way of using custom hook to handle onClick Event?
- Correct way to handle errors and display message in React using Hooks
- Correct way to make single conditional call to React Hooks' useFetch function?
- With React what is the best way to handle conditional classes
- What is the correct way to handle an accesstoken with react to secure routes?
- What is correct way to render conditional jsx when using redux with react
- The correct way of using useReducer to handle open/close of multiple dialogs in React
- React + Redux - What's the best way to handle CRUD in a form component?
- Correct way to share functions between components in React
- React - What is the best way to handle login and authentication?
- What is the correct way of adding a dependency to react in your package.json for a react component
- Correct way to define an empty dom element in React
- React i18next and correct way of changing language
- Correct way to throttle HTTP calls based on state in redux and react
- Correct way to handle undefined declaration files (index.d.ts)
- What is the correct way to animate/transition between routes in react router
- Correct way to define handlers in functional React components?
- React class components - conditional styling based on props
- What is the correct way to change Navbar values in React based on if user is logged in?
- What is the correct way to define a React component's contextTypes in TypeScript?
- Correct way to remove key from react state
- React - correct way to wait for page load?
- React JS - What is a good way to handle children click event?
- React best way to handle empty object before mount?
- React - Correct way of passing a reference to a react-portal
- Correct way to call passport js function from react component
- react set state callback correct way to pass an argument
- Correct way to pass functions to handlers in 'dumb' components in React
More Query from same tag
- Using the label prop for FormControlLabel
- Generate items into galley
- How can I define a variable in loop render html reactjs
- How can I pass props down to a child component that is wrapped in a container using reselect?
- React Child Component Not Rendering
- React.lazy not working in production mode
- Cookies between localhost and google app engine (custom google domain) not persistant
- React useEffect infinite loop fetch data axios
- Invariant Violation: Element type is invalid: expected a string or a class/function but got: undefined
- React Unable to Change Checkboxes
- React Authentication using HOC
- How to find Popup state and refresh state in React-router?
- How can I used Radium in react js
- Action-text-attachment tag not displaying on React front end
- How to display a ref variable without using state in React?
- jest.mock is not a function in react?
- React SVG Manipulation [Electron] (change color if DB is connected)
- Allow only numbers not starting with zero
- Uncaught Invariant Violation on saving to redux store second time
- Background image in div is not taking entire view
- Component doesn't re-render when Redux state is changed - React
- React Loading in Stylesheet only when Component is loaded
- How to display HTML code in REACT webpage without affecting the styles?
- How to organize partial entities in normalized redux store?
- Vite and React: stop using "react-refresh"
- can't render react js component inside datatables column render function
- React Hook UseEffect in combination with Firebase creating infinite loop
- pass object from state as props to child component
- async inside useEffect react
- SVGs don't show on Firefox