This could be achieved with a hook. However, I would not recommend it, as it strictly couples state and layout.
const useInput = (placeholder, initial) => {
const [value, setVal] = useState(initial)
const onChange = (e) => setVal(e.target.value)
const element = <input value={value} onChange={onChange} placeholder={placeholder}/>
return {element, value}
}
Use it in any functional component
const BensPlayGround = () => {
const name = useInput("Enter name here")
return (
<>
{name.element}
<h1>Hello {name.value}</h1>
</>
)
}
const useDataBind = () => {
const [value, setVal] = useState("")
const onChange = (e) => setVal(e.target.value)
return {value, onChange}
}
const Demo = (props) => {
const nameProps = useDataBind()
return (
<>
<input {...nameProps} placeholder="Enter name here" />
<h1>Hello {nameProps.value}</h1>
</>
)
}