Add a State Property to an Inline Style in React

Add a State property to an Inline Style in React

You can do it like this

style={ { width: `${ this.state.percentage }%` } }

Example

How to make inline style use state in React?

If you want to conditionally show items, i would use an array and check the value.



See it live!


const displayMap = {
false: 'none',
true: 'block'
}

class Home extends Component {
state = {
display: []
}

showMessage = (name) => {
this.setState({
display: [...this.state.display, name]
})
}

componentDidMount(){
setTimeout(()=> this.showMessage('hello'), 2500);
setTimeout(() => this.showMessage('name'), 20000);
setTimeout(() => this.showMessage('full-stack'), 10000);
}

render(){
const { display } = this.state
return(
<div className='home-div'>
<h2 className='hello-header' style={{display: displayMap[display.indexOf('hello') >= 0]}}>Hello, I'm</h2>
<h2 className='name-header' style={{display: displayMap[display.indexOf('name') >= 0]}}>Sean</h2>
<h2 className='full-stack-header' style={{display: displayMap[display.indexOf('full-stack') >= 0]}}>I'm a Full Stack Web Developer.</h2>
<a className='resume'>Download my resume here!</a>
<a className='github'>View my GitHub here!</a>
<h1 className='arrow'>⇩</h1>
</div>
)
}
}

React.js inline style best practices

There aren't a lot of "Best Practices" yet. Those of us that are using inline-styles, for React components, are still very much experimenting.

There are a number of approaches that vary wildly: React inline-style lib comparison chart

All or nothing?

What we refer to as "style" actually includes quite a few concepts:

  • Layout — how an element/component looks in relationship to others
  • Appearance — the characteristics of an element/component
  • Behavior and state — how an element/component looks in a given state

Start with state-styles

React is already managing the state of your components, this makes styles of state and behavior a natural fit for colocation with your component logic.

Instead of building components to render with conditional state-classes, consider adding state-styles directly:

// Typical component with state-classes
<li
className={classnames({ 'todo-list__item': true, 'is-complete': item.complete })} />

// Using inline-styles for state
<li className='todo-list__item'
style={(item.complete) ? styles.complete : {}} />

Note that we're using a class to style appearance but no longer using any .is- prefixed class for state and behavior.

We can use Object.assign (ES6) or _.extend (underscore/lodash) to add support for multiple states:

// Supporting multiple-states with inline-styles
<li 'todo-list__item'
style={Object.assign({}, item.complete && styles.complete, item.due && styles.due )}>

Customization and reusability

Now that we're using Object.assign it becomes very simple to make our component reusable with different styles. If we want to override the default styles, we can do so at the call-site with props, like so: <TodoItem dueStyle={ fontWeight: "bold" } />. Implemented like this:

<li 'todo-list__item'
style={Object.assign({},
item.due && styles.due,
item.due && this.props.dueStyles)}>

Layout

Personally, I don't see compelling reason to inline layout styles. There are a number of great CSS layout systems out there. I'd just use one.

That said, don't add layout styles directly to your component. Wrap your components with layout components. Here's an example.

// This couples your component to the layout system
// It reduces the reusability of your component
<UserBadge
className="col-xs-12 col-sm-6 col-md-8"
firstName="Michael"
lastName="Chan" />

// This is much easier to maintain and change
<div class="col-xs-12 col-sm-6 col-md-8">
<UserBadge
firstName="Michael"
lastName="Chan" />
</div>

For layout support, I often try to design components to be 100% width and height.

Appearance

This is the most contentious area of the "inline-style" debate. Ultimately, it's up to the component your designing and the comfort of your team with JavaScript.

One thing is certain, you'll need the assistance of a library. Browser-states (:hover, :focus), and media-queries are painful in raw React.

I like Radium because the syntax for those hard parts is designed to model that of SASS.

Code organization

Often you'll see a style object outside of the module. For a todo-list component, it might look something like this:

var styles = {
root: {
display: "block"
},
item: {
color: "black"

complete: {
textDecoration: "line-through"
},

due: {
color: "red"
}
},
}

getter functions

Adding a bunch of style logic to your template can get a little messy (as seen above). I like to create getter functions to compute styles:

React.createClass({
getStyles: function () {
return Object.assign(
{},
item.props.complete && styles.complete,
item.props.due && styles.due,
item.props.due && this.props.dueStyles
);
},

render: function () {
return <li style={this.getStyles()}>{this.props.item}</li>
}
});

Further watching

I discussed all of these in more detail at React Europe earlier this year: Inline Styles and when it's best to 'just use CSS'.

I'm happy to help as you make new discoveries along the way :) Hit me up -> @chantastic

React inline styles, applying styles from state

From React Docs:

In React, inline styles are not specified as a string. Instead they are specified with an object whose key is the camelCased version of the style name, and whose value is the style's value, usually a string.

It looks like you're most likely trying to set styles for a button that exists in components that are rendered in RouteHandler.

If that's the case, it would make the most sense for you to create a wrapper that wraps the other components and accepts the styles you're trying to set.

For example:

var PageWrapper = React.createClass({
setHeaderStyle: function(data){
var headerStyles = this.state.defaultStyles;
if(data) {
headerStyles.backgroundColor = data.first_colour;
headerStyles.color = data.theme;
}
this.setState({
branding: data,
headerStyles: headerStyles
});
},
render: function () {
var buttonStyle = {
color: this.state.color
}
return (
<RouteHandler buttonStyle={buttonStyle} />
);
}
});

var Index = React.createClass({
render: function () {
return (
<div>
<RouteHandler />
</div>
);
}
});

var Signup = React.createClass({
render: function() {
return (
<div>
<p> Click below to signup now! </p>
<button style={this.props.buttonStyle}>Click Me!</button>
</div>
);
}
});

var Contact = React.createClass({
render: function() {
return (
<div>
<p> Click the button below to contact us </p>
<button style={this.props.buttonStyle}>Email Us!</button>
</div>
);
}
});

var routes = (
<Route path="/" handler={Index}>
<Route path="page" handler={PageWrapper}>
<Route path="signup" handler={Signup} />
<Route path="contact" handler={Contact} />
</Route>
</Route>
);

ReactRouter.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});

Edit: Per your request, as an example to show how nested routes would work, I added a Signup and Contact component. If you look at the routes variable you can see how I nested these components under PageWrapper.

Now the nested routes /#/page/signup and /#/page/contact will both get access to the props that are added to the <RouteHandler /> of PageWrapper. Hope this helps!!!!!

react how to pass props to inline css style in components

Passing color will make the text inside the div of that color.

What you need it backgroundColor to make "colored squares".

Also, you can't pass an object to a styles, it need to be a string.

return (
<div
style={{ backgroundColor: `rgba(${Object.values(this.props.color).join(", ")})`, width: "36px", height: "36px" }}
/>
);

React: how to add css transition into inline style

I think you must write as follows:

  const slideStyle = {
width: 400 + "%",
marginLeft: dis + "px",
transition: "margin-left 1s"
};

Trying to change React Style attribute by changing state hook

React inline style doesn't know the !important property. There is usually always a way to avoid using it, and it is better to do so.

If you just don't avoid using !important, it will work here.

If you have to set it, this would work:

import React, { useState } from 'react';

const Carousel = () => {
let [selectedIndex, setSelectedIndex] = useState(0);
let [transform, setTransform] = useState({ color: 'red' });

const prevButton = () => {
setSelectedIndex(selectedIndex - 1);
setTransform({ ...{ color: 'green' } });
// rotateCarousel();
console.log(selectedIndex);
console.log(transform);
};

const nextButton = () => {
setSelectedIndex(selectedIndex + 1);
setTransform({ ...{ color: 'red' } });
console.log(transform);
// rotateCarousel();
};
return (
<>
<div className="scene">
<div
ref={el => {
if (el) {
el.style.setProperty('color', transform.color, 'important');
}
}}
className="carousel"
>
<div className="carousel__cell">1</div>
{transform.color}
<div className="carousel__cell">2</div>
<div className="carousel__cell">3</div>
<div className="carousel__cell">4</div>
<div className="carousel__cell">5</div>
<div className="carousel__cell">6</div>
<div className="carousel__cell">7</div>
<div className="carousel__cell">8</div>
<div className="carousel__cell">9</div>
</div>
</div>
<button onClick={prevButton}>Previous</button>
<button onClick={nextButton}>Next</button>
{transform.color}
</>
);
};

export default Carousel;

Conditional inline style in react js

You only want to pass a single style prop to a component. By passing two, the second one is overriding the first one, causing your display style to never make it to the styles:

<Button
size="small"
style={{
display: this.state.task.status == "Completed" ? "none": "",
textColor,
}}
>
Mark as Completed
</Button>

I support @MRchief's answer as well: in React, if you don't want to show an element, you shouldn't render it, unless you specifically need it hidden on the page for some reason (such as a hidden input).

Inline CSS styles in React: how to implement a:hover?

I'm in the same situation. Really like the pattern of keeping the styling in the components but the hover states seems like the last hurdle.

What I did was writing a mixin that you can add to your component that needs hover states.
This mixin will add a new hovered property to the state of your component. It will be set to true if the user hovers over the main DOM node of the component and sets it back to false if the users leaves the element.

Now in your component render function you can do something like:

<button style={m(
this.styles.container,
this.state.hovered && this.styles.hover,
)}>{this.props.children}</button>

Now each time the state of the hovered state changes the component will rerender.

I've also create a sandbox repo for this that I use to test some of these patterns myself. Check it out if you want to see an example of my implementation.

https://github.com/Sitebase/cssinjs/tree/feature-interaction-mixin



Related Topics



Leave a reply



Submit