6

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>
    );
  }
}
0

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a ton. With e.target the result was weird - null sometimes. Plus, it took forever to return the correct value.
You're welcome! Nice to see an answer from 2017 helping out someone after all that time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.