In my Class component App.jsx
I have the following function:
JavaScript
x
9
1
import { Position } from "./Position";
2
3
4
getPositionData = val => {
5
const { players } = this.props;
6
var res = players.filter(o=>Object.values(o).includes(val))
7
return res
8
};
9
Which is being handled at render()
when I click on a subcomponent inside a <div>
, like so:
JavaScript
1
6
1
<div className="field-row">
2
{this.getPlayersByPosition(players, 4).map((player,i) => (
3
<Position key={i} handleClick={this.getPositionData}>{player.name}</Position>
4
))}
5
</div>
6
On its turn, Position.jsx
handles onClick()
:
JavaScript
1
11
11
1
export const Position = props => (
2
<div
3
className={`position-wrapper ${
4
isManager(props.children) ? null : "field"
5
}`}
6
onClick={() => props.handleClick(props.children)}
7
>
8
{props.children}
9
</div>
10
);
11
But now I’d like to handle a second function when <div>
is clicked, say:
JavaScript
1
4
1
toggleFullScreen() {
2
this.setState({ fullScreen: !this.state.fullScreen });
3
}
4
which I would pass, on its own, like so:
JavaScript
1
2
1
onClick={this.toggleFullScreen.bind(this)}
2
How do I handle BOTH functions onClick()
at once in
JavaScript
1
4
1
<div className="field-row">
2
3
</div>
4
?
Advertisement
Answer
Just like you can invoke multiple functions at once in a JS listener with
JavaScript
1
5
1
element.addEventListener('click', () => {
2
fn1();
3
fn2();
4
});
5
You can do the same thing in React by defining the onClick
to be a function which invokes both:
JavaScript
1
6
1
<Position
2
key={i}
3
getPositionData={this.getPositionData}
4
toggleFullScreen={toggleFullScreen}
5
>{player.name}</Position>
6
JavaScript
1
14
14
1
export const Position = props => (
2
<div
3
className={`position-wrapper ${
4
isManager(props.children) ? null : "field"
5
}`}
6
onClick={() => {
7
props.getPositionData(props.children);
8
props.toggleFullScreen();
9
}}
10
>
11
{props.children}
12
</div>
13
);
14