I'm trying to change my state alignment to: left, center, right or justify, depending on which <Icon />
I've clicked. But, e.target.getAttribute('data-value')
is returning null
.
When I change <Icon icon="align-left" />
by left
, it's working. e.target.getAttribute('data-value')
is returning data-value.
So, how can I change my state to left, right center or justify on click of my <Icon />
?
class TextStyleParams extends React.Component {
constructor(props) {
super(props);
this.onClickAlignment = this.onClickAlignment.bind(this);
this.state = {
textStyle: {
alignment: 'left',
...,
},
};
}
onClickAlignment(e) {
const { textStyle } = this.state;
const newTextStyle = {
...textStyle,
alignment: e.target.getAttribute('data-value'),
};
this.setState({ textStyle: newTextStyle });
this.props.updateTextStyle(newTextStyle);
}
render() {
const { textStyle } = this.state;
return (
<div>
<span role="button" onClick={this.onClickAlignment} data-value="left"><Icon icon="align-left" /></span>
<span role="button" onClick={this.onClickAlignment} data-value="center"><Icon icon="align-center" /></span>
<span role="button" onClick={this.onClickAlignment} data-value="right"><Icon icon="align-right" /></span>
<span role="button" onClick={this.onClickAlignement} data-value="justify"><Icon icon="align-justify" /></span>
</div>
);
}
}
class Icon extends React.Component {
render() {
const { icon } = this.props;
return (
<svg viewBox="0 0 24 24" styleName="icon" className={`icon-${icon}`}>
<use xlinkHref={`iconset.svg#${icon}`} />
</svg>
);
}
}
Try using e.currentTarget.getAttribute('data-value')
. The target
property refers to the dom element on which the event originated (which will be the svg
element), whereas currentTarget
refers to the element to which the handler was attached.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With