Reputation: 382
I am working with a custom library where I need to set the cursor selection manually. Here is the code for my input:
import React, { useState } from 'react';
import { useDrag } from 'react-dnd'
import { Validation } from "../types";
...
<input
ref={forwardRef}
id={id}
type={type}
placeholder={placeholder}
value={value}
onChange={onChange}
onKeyDown={onKeyDown}
onBlur={onBlur}
name={name}
disabled={disabled}
className={`fb-form-control goggo ${validation?.type}`}
checked={!!checked}
draggable={true}
onDragStart={(event) => event.preventDefault()}
onMouseEnter={()=>console.error("onMouseEnter", "onMouseEnter")}
onMouseLeave={() => console.error("onMouseLeave", "onMouseLeave")}
onDoubleClick={() => console.error("I have been double clicked!")}
/>
I need to replace the () => console.error("I have been double clicked!")
with a call to a function that will select the text of the input. This code: onDoubleClick={() => console.error("this", document.getElementById(String(id))?.select())}
causes a "TS2551: Property 'select' does not exist on type 'HTMLElement'. Did you mean 'onselect'?
"
Upvotes: 3
Views: 184
Reputation: 7520
Use the event target instead of getElementById.
onDoubleClick={(event) => (event.target as HTMLInputElement).select()}
Upvotes: 1
Reputation: 2922
you can use window.getSelection
to select the text of the input:
onDoubleClick={() => {
const input = document.getElementById(String(id)) as HTMLInputElement;
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(input);
selection.removeAllRanges();
selection.addRange(range);
}}
Upvotes: 1