Search code examples
reactjsreact-bootstrap-typeahead

Update input text in react bootstrap typeahead from javascript/react


Hello I'm trying to create a react bootstrap typeahead in which I can update my input text from javascript. It works in console but doesn't work in code.

let typeaheadInput = document.getElementById('exTypeahead')
typeaheadInput.value = typeaheadInput.value + 'some text'

Is there any other way where we can insert text in the typeahead input box

import React from 'react';
import { Typeahead } from "react-bootstrap-typeahead";

const data = [
    {id: 1, fullName: 'John'},
    {id: 2, fullName: 'Peter'},
    {id: 3, fullName: 'Blaszczykowski'},
    {id: 4, fullName: 'lewandowski'},
]

class TypeaheadComp extends React.Component {

    constructor(props){
        super(props)
        this.state = {
            selectedList: []
        }
    }

    render() {
        return <Typeahead
                id="basic-example"
                onChange={(selected) => {
                    let temp = [];
                    selected.map(x => {
                        temp.push(x);
                    });
                    this.setState({selectedList: temp})

                }}
                options={data}
                placeholder="Select name or create full name"
                selected={this.state.selectedList}
                labelKey="fullName"
                multiple
                allowNew
                newSelectionPrefix="Enter full name: "
                inputProps={{id:'exTypeahead'}}
            />;
    }
}

export default TypeaheadComp

Solution

  • The defaultInputValue prop can be used to set the input value on the initial render, but the component intentionally does not provide a public API for setting the input value in a controlled manner.

    Workarounds

    Note: Both of these workarounds are highly discouraged.

    1. You could leverage defaultInputValue by un-mounting and re-mounting the component (eg: by changing the key) with a new default input value on each new mount. This is pretty heavy-handed and could lead to performance issues or bugs.
    const [key, setKey] = useState(0);
    const [value, setValue] = useState('');
    
    return (
      <Typeahead
        ...
        defaultInputValue={value}
        key={key}
        onBlur={(e) => {
          setValue('some value');
          setKey(key + 1);
        }}
      />
    );
    
    1. You could access the component instance with a ref and use the setState method to update the component state's text key. This is obviously not recommended since setState is private, is very fragile, and could break at any time
    const ref = useRef(null);
    
    return (
      <Typeahead
        ...
        onBlur={() => {
          ref.current.setState({
            text: 'some value',
          });
        }}
        ref={ref}
      />
    );