P
P
PlasterTom2018-03-29 19:52:55
React
PlasterTom, 2018-03-29 19:52:55

What are props explicitly for?

Why is the first line in the functional component explicitly listing properties {comments=[], isOpen, toggleOpen} instead of (props)? Does it have to do with using a decorator?

function CommentList ({comments=[], isOpen, toggleOpen}){
    const text = isOpen ? 'hide comments': 'show comments'
        return(
            <div>
                <button onClick={toggleOpen}>{text}</button>
                {getBody(comments,isOpen)}
            </div>
        )
}

function getBody(comments,isOpen) {
    if (!isOpen) return null
    if (!comments.length) return (
    <div>
        <p>No comments yet</p>
    </div>
    )
    return (
    <div>
        <ul>
            {comments.map(comment => <li key={comment.id} ><Comment comment={comment}/></li>)}
        </ul>
    </div>
    )
}

export default toggleOpen(CommentList)

And actually I have a second question about how a decorator works. Line
<OriginalComponent {...this.props} isOpen={this.state.isOpen} toggleOpen={this.toggleOpen}/>
- what ...this.props are passed here? WrappedComponent huh? What props does he have?
export default (OriginalComponent)=> class WrappedComponent extends Component {
    
    state = {
        isOpen: false
    }

 toggleOpen = (ev) => {
     ev && ev.preventDefault && ev.preventDefault()
        this.setState({
         
          commnetsIsOpen: !this.state.commnetsIsOpen  
        })
    }
    render() {
        return <OriginalComponent {...this.props} isOpen={this.state.isOpen} toggleOpen={this.toggleOpen}/>
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vlad_kopylov, 2018-03-29
@PlasterTom

This is called object destructuring.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question