Search code examples
javascriptreactjsonclickreact-router-redux

On Block Click Event


I have a container that is a set of buttons, but let us just observe the component as a single component. This component has an onBlockClick which receives the id for where to go.

I would like to transform id to be a registrationSomeContainer.

My problem is, how can I address other container from the onBlockClick?

let registrationContainer = ({
    i18n,
    id,
    name,
    representative,
    onBlockClick,
    dispatch
}) => {

    return (
        <div>
            <div
                className="app_wrapper"
            >
                <Block
                    leftIcon="close"
                    lines={[
                        "Some",
                        representative
                    ]}
                    onBlockClick(id)
                />
            </div>
        </div>
    )

}

Solution

  • A less performant way is

    const registrationContainer = ({
        i18n,
        id,
        name,
        representative,
        onBlockClick,
        dispatch
    }) => {
        return (
            <div className="app_wrapper">
                <Block
                    leftIcon="close"
                    lines={[
                        "Some",
                        representative
                    ]}
                    onBlockClick={onBlockClick.bind(null, id)}
                />
            </div>
        );
    }
    

    A more optimized Code could be

    const registrationContainer = ({
        i18n,
        id,
        name,
        representative,
        onBlockClick,
        dispatch
    }) => {
        return (
            <div className="app_wrapper">
                <Block
                    id={id} // Look: passing id
                    leftIcon="close"
                    lines={[
                        "Some",
                        representative
                    ]}
                    onBlockClick={onBlockClick} // Look: not binding
                />
            </div>
        );
    }
    
    class Block extends Component {
        handleClick = (e) => {
            this.props.onBlockClick(this.props.id);
        };
    
        render() {
            <div onClick={this.handleClick}>
    
            </div>
        }
    }
    

    Why is binding the bad way

    Binding onBlockClick={onBlockClick.bind(null, id)} makes onBlockClickget new reference everytime so caused the children component to re render. Read more from here https://daveceddia.com/avoid-bind-when-passing-props/