Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - how to create attributes dynamically

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;
 }
like image 786
sandrina-p Avatar asked May 03 '26 01:05

sandrina-p


1 Answers

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>
    );
}
like image 80
Jeff McCloud Avatar answered May 04 '26 17:05

Jeff McCloud



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!