Change state in another component

1972 views javascript
4

I am trying to get the the variable heartIconColor to be used in my child component. But I am getting an error. How can I get this variable to be the color of the icon?

ReferenceError: Can't find variable: heartIconColor

My app.js

export default class Home extends Component {
  constructor(props){
    super(props);
    this.state = {
      liked: false
    }
  }
  likePost = (author, id) => {
    alert("Liked!!" + author + id)
    this.liked()
  }
  liked(){
    this.setState({
      liked: !this.state.liked
    })
  }
  renderItem = ({ item, index }) => {
    return (
      <Post
        like={this.likePost} 
        liked={this.state.liked}
      />
    )
  }
  render() {
    const heartIconColor = this.state.liked ? "red" : null;
    return (
     <FlatList data={this.state.getData} renderItem={this.renderItem}>
     </FlatList>
    )
  }

My component:

const Post = (props) => {
const styles = StyleSheet.create({
heartIcon: {
      fontSize: 20,
      color: heartIconColor,
    }
})
return (
<View style={styles.flex}>
          <Text><Icon onPress={() => onClick={this.props.like}} style={styles.heartIcon} type="Octicons" name="heart" /></Text>
</View>
)
}
export { Post };

answered question

Pass heartIconColor as a prop into your Post component?

@CodyCaughlan Yeah, correct!

1 Answer

7

You can get your icon color as

const styles = StyleSheet.create({
heartIcon: {
      fontSize: 20,
      color: props.liked ? "red" : null,
    }
})

posted this

Have an answer?

JD

Please login first before posting an answer.