3

I have 2 attributes connected to 2 props: aria-hidden and aria-label.
When aria-hidden is true, it only shows that one. If it's false, it shows only aria-label.

I wrote this code but it's not DRY... How can I improve it?

 render() {
     let svgMarkup = '';

        if (this.props.hidden) {
            svgMarkup = (
                <svg role="img" aria-hidden="true">
                    ...
                </svg>
            );
        } else {
            svgMarkup = (
                <svg role="img" aria-label={ this.props.label }>
                    ...
                </svg>
            );
        }

        return svgMarkup;
 }

1 Answer 1

10

You can set the props on a plain object, then apply the props to your react component using spread syntax:

render() {
    const ariaProps = this.props.hidden ?
        { 'aria-hidden': 'true' }
        :
        { 'aria-label': this.props.label };

    return (
        <svg role="img" {...ariaProps}>
            ...
        </svg>
    );
}
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome! I was trying to do something similar but failed on ... part. Thanks!
No worries, glad to help! Yes, that spread operator comes in handy!!
I my case spread operator is not working and showing unexpected token error

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.