Ad

How To Pass Value To Component Which I Get From Another By OnClick Event

- 1 answer

I'm a newbie in react. So sorry) I created my icon component which has svg icons inside:

<IconPick icon={'globe'} />

then I created array of icons' names:

iconsList = ['globe', 'mail', ...];

And map through this component to show all icons that I have in one block:

<ul className="icons-list__wrapper">
    {iconsList.map(icon =>
        <li data-icon={icon} key={icon}>
            <IconPick icon={icon} />
        </li>
    )}
</ul>

Everything is working fine. Now I want to make from this block kind of Icon Picker. So when person click on any icon it will be appeared in a new block, so I used onClick:

    handleCheck = (e) => {
        e.currentTarget.dataset.icon
    }
...
    <div>
        <ul className="icons-list__wrapper">
            {iconsList.map(icon =>
                <li
                data-icon={icon}
                key={icon}
                onClick={this.handleCheck}
                >
                    <IconPick icon={icon} />
                </li>
            )}
        </ul>
    </div>
...

So now I create a new div in which I want to pass data value that I get onClick into clickedIcon:

<div>
    <IconPick icon={clickedIcon}/>
</div>

But I can't do it right, can you help me? Or just advice.

I will be very grateful.

Ad

Answer

You can define the clickedIcon as state of the component.

state={
   clickedIcon:undefined // initially it is undefined
}

In your handler you update the clickedIcon value :

handleCheck = icon => this.setState({clickedIcon : icon});

Pass the icon clicked value :

<li
     data-icon={icon}
     key={icon}
     onClick={()=>this.handleCheck(icon)}>
   <IconPick icon={icon} />
</li>

And finally you can pass the clickedIcon value to your IconPick easily :

<div>
    <IconPick icon={this.state.clickedIcon}/>
</div>
Ad
source: stackoverflow.com
Ad