redpanda2236
redpanda2236

Reputation: 184

Material UI SearchBar value tag causes error: "this" is undefined

The example usage of material-UI's <SearchBar /> does not work for me. The code I am attempting to run is.

import SearchBar from "material-ui-search-bar";
 
function App() {
  return (
    <SearchBar
      value={this.state.value}
      onChange={(newValue) => this.setState({ value: newValue })}
      onRequestSearch={() => doSomethingWith(this.state.value)}
    />
  );
}

Which I got from https://www.npmjs.com/package/material-ui-search-bar And I get this error

TypeError: this is undefined
App
src/components/App.js:20

  17 | // );
  18 | return (
  19 |   <SearchBar
> 20 |     value={this.state.value}
     | ^  21 |     onChange={(newValue) => this.setState({ value: newValue })}
  22 |   />
  23 | );

renderWithHooks
node_modules/react-dom/cjs/react-dom.development.js:14985
mountIndeterminateComponent
node_modules/react-dom/cjs/react-dom.development.js:17811
beginWork
node_modules/react-dom/cjs/react-dom.development.js:19049
callCallback
node_modules/react-dom/cjs/react-dom.development.js:3945
invokeGuardedCallbackDev
node_modules/react-dom/cjs/react-dom.development.js:3994
invokeGuardedCallback
node_modules/react-dom/cjs/react-dom.development.js:4056
beginWork$1
node_modules/react-dom/cjs/react-dom.development.js:23964
performUnitOfWork
node_modules/react-dom/cjs/react-dom.development.js:22776
workLoopSync
node_modules/react-dom/cjs/react-dom.development.js:22707
renderRootSync
node_modules/react-dom/cjs/react-dom.development.js:22670
performSyncWorkOnRoot
node_modules/react-dom/cjs/react-dom.development.js:22293
scheduleUpdateOnFiber
node_modules/react-dom/cjs/react-dom.development.js:21881
updateContainer
node_modules/react-dom/cjs/react-dom.development.js:25482
legacyRenderSubtreeIntoContainer/<
node_modules/react-dom/cjs/react-dom.development.js:26021
unbatchedUpdates
node_modules/react-dom/cjs/react-dom.development.js:22431
legacyRenderSubtreeIntoContainer
node_modules/react-dom/cjs/react-dom.development.js:26020
render
node_modules/react-dom/cjs/react-dom.development.js:26103

When I remove the "value={this.state.value}" part the error is resolved, what is the correct way to declare and use "value"?

Upvotes: 0

Views: 221

Answers (1)

Giovanni Esposito
Giovanni Esposito

Reputation: 11166

Your App is a functional component so you need to rewrite your component ins this way:

import React, { useState } from 'react';

function App() {
  const [value, setValue] = useState(""); 
  return (
    <SearchBar
      value={value}
      onChange={(newValue) => setValue(newValue)}
      onRequestSearch={() => doSomethingWith(value)}
    />
  );
}

Upvotes: 3

Related Questions