aman
aman

Reputation: 391

Set Attribute to html tag without a value

I'm trying to set an attribute without value to a custom HTML element. I do not want to achieve this dynamically using the JavaScript function setAttribute. I specifically want to set an attribute through a class variable "status" without any value. I currently am using an attribute with the value of "status" which I do not want to use: <container status={this.status}></container> -> <container status="type1"></container>.

I believe this may not be possible but I really want to achieve this. So I want to hear any strategy in achieving this. Thanks

component.tsx

class Comp extends React.Component<any, any> {

    status: "type1" | "type2" | "type3" = "type1";

    render() {
        return(
            <container {this.status}></container>
        );
    }
}
export default Comp;

desired HTML output

<container type1></container>

Upvotes: 1

Views: 976

Answers (2)

Black Mamba
Black Mamba

Reputation: 15615

You can do something like this:

class Comp extends React.Component<any, any> {

    status: "type1" | "type2" | "type3" = "type1";


    render() {
        return(
            <container {...{[this.status]: true}}></container>
        );
    }
}
export default Comp;

Upvotes: 1

95faf8e76605e973
95faf8e76605e973

Reputation: 14201

You can generate an object (for dynamic attribute purposes) and pass an empty string to it. The output on the DOM will be an HTML5 attribute with no value.

var status = {type1: ''};

render() {
    return(
        <container {...status}></container>
    );
}

Upvotes: 1

Related Questions