Reputation: 49
I'm trying to use a color as a prop in a reactjs setting. In the General_heading component, I want to be able to pass a prop to define the color of the heading, but I can't get it to respond currently. Thoughts? in app.js:
<div><General_header theme_color="red"/></div>
in General_header.js:
import React, { Component } from 'react';
class General_header extends React.Component {
constructor(props) {
super(props);
this.state = {logo_img: props.logo_img,
theme_color: props.theme_color};
}
render() {
return (
<div style={[styles.header,{backgroundColor:this.state.theme_color}]}>test
<img src={this.state.logo_img} alt={'logo'} style={styles.logo_img} />
</div>
);
}
}
var styles = {
header: {
height: '100px',
display: 'block'},
logo_img: {
height: '40px',
display: 'inline-block'}
}
export default General_header;
Upvotes: 0
Views: 12040
Reputation: 13807
Made some changes below to your code:
class General_header extends React.Component {
render() {
// This will create a single object containing fields
// from styles.header plus the extra backgroundColor field.
const fullStyle = {
...styles.header, // This is called the spread operator
backgroundColor: this.props.theme_color // No need to assign this to state
}
return (
<div style={fullStyle}>test
<img src={this.state.logo_img} alt={'logo'} style={styles.logo_img} />
</div>
);
}
}
ES5 version:
var fullStyle = Object.assign(
{},
styles.header,
{ backgroundColor: this.props.theme_color }
);
Upvotes: 0
Reputation: 22885
Use camelCase
Have a look at this https://github.com/airbnb/javascript/tree/master/react#naming
<GeneralHeader themeColor="red"/>
constructor(props) {
super(props);
this.state = {
logoImg: props.logoImg,
themeColor: props.themeColor
};
}
<div style={{backgroundColor: this.state.themeColor}}>
Upvotes: 1