I need an input component where I can insert text and when I enter a special character, a window appears with a choice of variables and it will be inserted as a tag, and this variable tag can be inserted anywhere in the text. As far as I understand, this should be done with contentEditable.
all I could do is such an input, where I put the $ symbol only at the end, and not a tag is added, but text:
I found many examples where there is just adding tags (https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/), but I didn’t find such a component where tags are mixed with text, can anyone see this?
import { useState } from 'react'
import classNames from 'classnames'
import ContentEditable from 'react-contenteditable'
import { useAppSelector } from '../../app/hooks'
import { selectVariables } from '../../redux/reducers/variables'
import styles from '../../stylesheets/components/common/InputVariable.module.scss'
export const InputVariable = ({ className, label, onChange, value }: any) => {
const { variables } = useAppSelector(selectVariables)
const [symbol, symbolSet] = useState(false)
const handleChange = (e: any) => {
const str = e.target.value
onChange(str)
if (str.charAt(str.length - 1) === '$') {
symbolSet(true)
} else {
symbolSet(false)
}
}
const handleClickVariable = (variable: any) => {
const newStr = `${value.substring(0, value.length - 1)}{{${variable.id}}}`
onChange(newStr)
symbolSet(false)
}
const onPaste = (e: any) => {
e.preventDefault()
const text = e.clipboardData.getData('text/plain')
console.log(text)
}
return (
<div className={classNames(styles.inputVariable, className)}>
<span className={styles.label}>{label}</span>
<ContentEditable
className={styles.root}
html={value}
disabled={false}
onChange={handleChange}
onPaste={onPaste}
/>
{symbol && (
<div className={styles.variables}>
{variables &&
variables.map((variable: any) => (
<div key={variable.id} onClick={() => handleClickVariable(variable)} className={styles.variable}>
{variable.name}
</div>
))}
</div>
)}
</div>
)
}
export default InputVariable