Skip to content

Toggle style by clicking on button using styled-component

After onClick, it starts function onToggleLiked in app.js which toggle like property and return(or not) like to item.js. After that, AppListItem check if like has appeared, and use styles from const theme if the result is true, else – from defaultProps.

How to do that? I’ve tried to create a function, but failed.

let AppListItem = styled.div`
.fa-heart {
          transform: ${props => props.theme.ts};
          opacity: ${props => props.theme.op};
      }`

AppListItem.defaultProps = {
   theme: {
    op: "0",
    ts: "translateX(30px)"
}}

const theme = {
    op: "1",
    ts: "translateX(0px)"
}
export default class PostListItem extends Component {
    render() {
           const {like} = this.props;
           if (like) {?}

return (
        <AppListItem>
            <ItemLabel as="span"
            onClick={onToggleLiked}>
                {label}
            </ItemLabel>

Answer

You can simply spread the desired properties, depending on the liked condition.

render() {
   const { like } = this.props;
   const props = like ? { theme: theme } : AppListItem.defaultProps;
   return <AppListitem {...props}>....;
}