Reputation: 1939
I am curious if it is possible to set a style in react native to a variable that is set based on the result of an API hit?
So for example
let textColor = 'fake-api-getcolor'
<text style={{color: textColor}}>Hello</text>
And then have that API endpoint connected to a backend CMS where I would allow the user to choose a color.
I am not sure if this would be possible because of the app build/compile process?
Upvotes: 0
Views: 1875
Reputation:
set color in setState dynamically
this.state = {
backgroundColor: 'blue'
}
Upvotes: 0
Reputation: 2387
You can do this using state
class AppComponent extends React.Component {
state = {
textColor: "red"
}
async changeColor() {
const color = "blue" //Here you can fetch color from your api then call setState like below
this.setState({
textColor: color
})
}
render() {
const {
textColor
} = this.state;
return <text style={{color: textColor}}>Hello</text>
}
}
Upvotes: 1
Reputation: 4346
Yes it is possible.
You'll just treat it as any normal object and use it for your values or styling. See here for a complete explanation.
Upvotes: 2
Reputation: 1227
It is totally posible if you are fetching that value then setting the variable every time that is a change in the backend. I mean, yes, you can have computed values in the styles.
Upvotes: 1