(I am using JSX with ES6 syntax)
This works:
render() {
return (
<div style={{ width: '95%' }}></div>
)
}
This doesn't work: (why not?) Edit: It actually does work
render() {
return (
<div style={{ width: this.props.progress + '%' }}></div>
)
}
Edit:
It works but the style value has to be a valid value else it will return the error.
I use the state to create the style object and clean out the property with a regular expression in the constructor, so it will not be error-ing again because of invalid values. Here is my solution:
import React, { Component, PropTypes } from 'react'
export default class ProgressBar extends Component {
constructor(props) {
super(props)
let progress = +props.progress.replace(/[^0-9]/g, '') || 50
this.state = {
style: {
width: progress + '%'
}
}
}
render() {
return (
...
<div className="progress-bar" role="progressbar" aria-valuenow={ this.state.progress } style={ this.state.style }></div>
...
)
}
}
ProgressBar.propTypes = {
progress: PropTypes.string.isRequired
}
Props can be passed to styled components just as they are with regular React components (class or functional). This is possible because styled components are actually React components. styled-components creates a React component, which renders an HTML tag corresponding to the property in the styled object.
We use props in React to pass data from one component to another (from a parent component to a child component(s)). Props is just a shorter way of saying properties. They are useful when you want the flow of data in your app to be dynamic.
JSX gives us the convenience of combining HTML syntax and JavaScript under one file in React. However, our stylesheets always existed in a separate directory. With inline styles, you have to option to combine CSS syntax with JSX code.
Most likely this.props.progess
is not set to an appropriate value. Provide a good default for this case:
render() {
const { progress = 0 } = this.props;
return (
<div style={{ width: progress + '%' }}></div>
)
}
Your example works as you expected.
class Example extends React.Component {
render(){
const style = {
width: this.props.progress + '%',
backgroundColor : 'red'
}
return <div style={style}>
Hello
</div>
}
}
React.render(<Example progress={10}/>, document.getElementById('container'));
Fiddle
. Just make sure that you dont forget to set progress
prop with coresponding value
Update 2021 (Functional Component)
const Example = (props) {
const style = {
width: props.progress + '%',
backgroundColor : 'red'
}
return (
<div style={style}>Hello</div>
);
}
React.render(<Example progress={10}/>, document.getElementById('container'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With