React Bootstrap Typeahead

Chirag Bhavsar
3 min readOct 6, 2021

React Bootstrap Typeahead is a slick alternative to old style HTML Select Box. Github page has nice explanation and live examples are easy enough to follow.

In this article, I am going to show you one simple example based on Array of Strings and few problems I ran into and how I solved it.

There are several examples of Bootstrap Typeahead that exists but if you are looking for something very simple Array based example, very few exists.

Simple Example

I created a Simple Task Management App to explain this issue. Users come and create tasks and later edit tasks.

For this App to work, we need to have an array of Priorities (for Tasks)that need to be displayed and selected. Priorities is an array of Strings.

Typeahead Example
this.priorities = [ ‘High’, ‘ Medium’, ‘Low’];
............
............
<Typeahead placeholder="Choose Priority Type"options={this.priorities}
selected={this.state.task && this.state.task.priority} clearButton
onChange={(selected) => this.setState(state =>{let task = this.state.task;task.priority=selected[0];return ({...this.state, task: task})})}/>

If you are adding a new Task, the above code works perfectly fine.

Error 1: Cannot read properties of undefined

But, as soon as we Edit a task, it gives an error in Rendering itself. Here is the error, it gives:

Uncaught TypeError: Cannot read properties of undefined (reading ‘paginationOption’)

The reason for this error :this.state.task.priority is not an Array! The error doesn’t explain that. React Bootstrap expects it to be an Array. In my case, I created another state variable and assigned the variable. But, you can do it differently, if you need to.

.... axios call .....
let task = res.data;
let priority = [task.priority];
this.setState({task: task, priority: priority});
.....
.....
<Typeahead placeholder="Choose Priority Type"
options={this.priorities} selected={this.state.priority} clearButtononChange={(selected) => this.setState(state =>{let task = this.state.task;task.priority=selected[0];return ({...this.state, task: task, priority: selected})})}/>

Error 2: Not able to modify Data for Controlled Component

If you ever encounter that your Controlled component is not letting you modify Data, you need to start looking at if you are changing state variable in your onChange method.

For example, in above example, if you forgot to set priority in your state, then you will run into a problem.

<Typeahead placeholder="Choose Priority Type"options={this.priorities} selected={this.state.priority} clearButtononChange={(selected) => this.setState(state =>{let task = this.state.task;task.priority=selected[0];return ({...this.state, task: task, priority: selected})})}/>

Please let me know if you run into any other types of errors and how you overcome it.

Thanks for going through this article and I hope this was helpful.

--

--