0

This is my working react component. Here I have two functions getStyle and markComplete. What is the reason for getStyle to be called with brackets '()' like getStyle() and markComplete to be called without them?

 function TodoItem(props) {

    const getStyle = () => {
        return {
            backgroundColor: '#f4f4f4',
            padding: '10px',
            border: '1px #ccc dotted',
            textDecoration: props.todo.completed ? 'line-through' : 'none'
        }
    }

    const markComplete = (e) => {
        console.log(props.todo)
    }

    return (
        <div style={getStyle()}>
            <p>
                <input type="checkbox" onChange={markComplete} /> { }
                {props.todo.title}
            </p>
        </div>
    )
}

  • 1
    getStyle is called whenever the component is rendered but markComplete is called only when there is some change happen ()<- the bracket is used for calling the function – Arun Nov 19 '20 at 11:43
  • 1
    You should first ask yourself 'when do I want to call this function'? If you want to do it now, you simply add brackets like in `getStyle()` and you get immediate result. If you want to do it later, you pass a callback (reference to a function). In your example, If you did `markComplete(something)` directly in onChange prop, the function would be resolved immediately and the input would need to work on undefined value (markComplete does not return anything) – Rafał Bagrowski Nov 19 '20 at 11:46

0 Answers0