Home > Mobile >  Accessing the element's own attributes from another attribute
Accessing the element's own attributes from another attribute

Time:09-18

I have an input tag like this

export default function MyComponent(prop) {
    const [searchParams, setSearchParams]= useSearchParams();
    return (
        <input 
            className="css-checkbox" 
            type="checkbox" 
            id="cupcakes" 
            name="filterCupcakes" 
            checked={searchParams.has("filterCupcakes")}
        />
    );
}

Is there a way I can access the name attribute from within the checked attribute? Something like this:

<input 
    className="css-checkbox" 
    type="checkbox" 
    id="cupcakes" 
    name="filterCupcakes" 
    checked={searchParams.has(input.name)}
/>

(Btw if you have any suggestions for a better question name please comment them)

CodePudding user response:

Declare the name up front, and then reference that in both props.

export default function MyComponent() {
    const [searchParams, setSearchParams]= useSearchParams();
    const name = 'filterCupcakes';
    return (
        <input 
            className="css-checkbox" 
            type="checkbox" 
            id="cupcakes" 
            name={name}
            checked={searchParams.has(name)}
        />
    );
}

It doesn't make all that much sense for a single component that returns another static input, but the above is easily extensible by adding a prop to MyComponent that indicates the name you want for the input.

export default function MyComponent({ name }) {
    const [searchParams, setSearchParams]= useSearchParams();
    return (
        <input 
            className="css-checkbox" 
            type="checkbox" 
            id="cupcakes" 
            name={name}
            checked={searchParams.has(name)}
        />
    );
}
<MyComponent name="filterCupcakes" />
  • Related