React doesn't recognize function - javascript

I am trying this tutorial for the react chat and keep getting the error
TypeError: n.props.handleNewUserMessage is not a function
I tried to resolve it using the following resources:
https://www.reddit.com/r/reactjs/comments/6fd6nl/keep_getting_error_thispropsonsearch_in_not_a/?st=jhiugk4d&sh=fabd3cc4
ReactJS with ES6: this.props is not a function when I communicate two components
React TypeError this._test is not a function
React does not recognize my function
This is my code:
import React, { Component } from 'react';
import { Widget, addResponseMessage } from 'react-chat-widget';
import 'react-chat-widget/lib/styles.css';
class App extends Component {
componentDidMount() {
addResponseMessage("How can I help you?");
}
handleNewUserMessage = (newMessage) => {
console.log(`New message incomig! ${newMessage}`);
// Now send the message throught the backend API
addResponseMessage('response');
}
render() {
return (
<div className="App">
<Widget />
</div>
);
}
}
export default App;
Where have I gone wrong?

Just as the error mentions, you forgot to actually add the method to the props:
<Widget
handleNewUserMessage={this.handleNewUserMessage}
/>

Related

Console.Log Not Being Called Inside React Constructor

I'm trying to add a component to a default .NET Core MVC with React project. I believe I have everything wired up to mirror the existing "Fetch Data" component, but it doesn't seem like it's actually being called (but the link to the component in my navbar does move to a new page).
The component itself...
import React, { Component } from 'react';
export class TestComponent extends Component {
static displayName = TestComponent.name;
constructor (props) {
super(props);
console.log("WHO NOW?");
this.state = { message: '', loading: true, promise: null };
this.state.promise = fetch('api/SampleData/ManyHotDogs');
console.log(this.state.promise);
}
static renderForecastsTable (message) {
return (
<h1>
Current Message: {message}
</h1>
);
}
render () {
let contents = this.state.loading
? <p><em>Loading...</em></p>
: TestComponent.renderForecastsTable(this.state.message);
return (
<div>
<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>
{contents}
</div>
);
}
}
The App.js
import React, { Component } from 'react';
import { Route } from 'react-router';
import { Layout } from './components/Layout';
import { Home } from './components/Home';
import { FetchData } from './components/FetchData';
import { Counter } from './components/Counter';
import { TestComponent } from './components/TestComponent';
export default class App extends Component {
static displayName = App.name;
render () {
return (
<Layout>
<Route exact path='/' component={Home} />
<Route path='/counter' component={Counter} />
<Route path='/fetch-data' component={FetchData} />
<Route path='/test-controller' component={TestComponent} />
</Layout>
);
}
}
That console.log("Who now") is never called when I inspect, and the page remains totally blank. I can't find a key difference between this and the functioning components, and google has not been much help either. Any ideas what is missing?
Edit
While troubleshooting this, I ended up creating a dependency nightmare that broke the app. Since I'm only using the app to explore React, I nuked it and started over--and on the second attempt I have not been able to reproduce the not-rendering issue.
It is advisable to use componentDidMount to make the call to the REST API with the fetch or axios.
class TestComponent extends Component{
constructor(props){
state = {promise: ''}
}
async componentDidMount () {
let promise = await fetch ('api / SampleData / ManyHotDogs');
this.setState ({promise});
console.log (promise);
}
render(){
return(
<div>{this.state.promise}</div>
);
}
}

How to preserve referencies when Component is exported via a function?

Documentation describes how to add a ref to a class component when using ReactJS version 16.3+.
Here is a simplified and working example using two files:
MyForm.js file:
import React, { Component } from 'react';
import MyInput from "./MyInput";
class MyForm extends Component {
constructor(props) {
super(props);
this.myInput = React.createRef();
this.onClick = this.onClick.bind(this);
}
onClick(){
console.log(this.myInput.current.isValid());
}
render() {
return (
<div>
<MyInput ref={this.myInput} />
<button onClick={this.onClick}>Verify form</button>
</div>
);
}
}
export default MyForm;
MyInput.js file
import React, { Component } from 'react';
class MyInput extends Component {
isValid(){
return true;
}
render() {
return (
<div>
Name :
<input type="text" />
</div>
);
}
}
export default MyInput;
It works fine, console displays true when I click on MyForm button. But as soon as I add a function just before exporting my Component, errors are thrown. As example, I add a translation via react-i18n
MyInput.js file with export using a function
class MyInput extends Component {
isValid(){
return true;
}
render() {
const {t} = this.props;
return (
<div>
{t("Name")}
<input type="text" />
</div>
);
}
}
export default translate()(MyInput); // <=== This line is changing
Now, when I click on button, an error is thrown:
TypeError: this.myInput.current.isValid is not a function
The error disappear when I remove translate() in the last line.
I understood that the ref has been destroyed by the new component returned by translate function. It's an HOC. I read the Forwarding ref chapter, but I don't understand how to forward ref to the component returned by translate() function.
I have this problem as soon as I use translate from reacti18next and with the result of connect function from redux
I found a solution using onRef props and ComponentDidMount, but some contributors thinks this is an antipattern and I would like to avoid this.
Is there a way to create a wrapper that catch the HOC result of translate() or connect() and add ref to this HOC result ?

React & Redux: Uncaught TypeError: (0 , _reactRedux.connect) is not a function

I am new with redux, react and parceljs. I'm currently experimenting with this 3 stuff by doing the redux tutorial. And after parceljs did it job, when I went to the browser I got this error on the console:
Uncaught TypeError: (0 , _reactRedux.connect) is not a function
The code right now is
import { connect } from 'react-redux';
const AddTodo = ({dispatch}) => {
.
.
.
}
export default connect()(AddTodo)
I changed:
import { connect } from 'react-redux';
to:
import { connect } from 'redux';
and gave me basically same error.
What should I do in this case?
I checked the documentation and issues and the only issues I found about connect() is that you cannot use it as a decorator but that's it. Am I missing something I don't know yet?
(Sorry for my bad grammar in English, not my first language)
To use connect, you need to bind the component not an object. Thus, you may change your todo
const AddTodo = {
With:
const AddTodo = () => { // a stateless component
// now, you can return the object
return ( // just an example
<div>
<input type="text" />
</div>
)
}
And the connect is imported from react-redux:
import { connect } from 'react-redux'; // this is correct

React.js fetch Giphy API

I'm building a search engine (with React.js), where I can look for GIPHY gifs, using their API. I'm new to React.js and i'm having some trouble getting this code right.
import React from 'react'; //react library
import ReactDOM from 'react-dom'; //react DOM - to manipulate elements
import './index.css';
import SearchBar from './components/Search';
import GifList from './components/SelectedList';
class Root extends React.Component { //Component that will serve as the parent for the rest of the application.
constructor() {
super();
this.state = {
gifs: []
}
}
handleTermChange(term) {
console.log(term);
//---------------------->
let url = 'http://api.giphy.com/v1/gifs/search?q=${term}&api_key=dc6zaTOxFJmzC';
fetch(url).
then(response => response.json()).then((gifs) => {
console.log(gifs);
console.log(gifs.length);
this.setState({
gifs: gifs
});
});//<------------------------- THIS CODE HERE
};
render() {
return (
<div>
<SearchBar onTermChange={this.handleTermChange} />
<GifList gifs={this.state.gifs} />
</div>
);
}
}
ReactDOM.render( <Root />, document.getElementById('root'));
I get the following error in the console:
Uncaught (in promise) TypeError: _this2.setState is not a function
at eval (index.js:64)
at
Any help is appreciated :) Thanks!
this is not auto-bound in ES6 style syntax.
You have to bind in the constructor:
```
super();
this.state = {
gifs: []
}
this.handleTermChange = this.handleTermChange.bind(this)```
or use arrow function syntax for the function in question:
func = () => {};
For reference: https://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding

Issue using AsyncTypeahead from react-bootstrap-typeahead package

I'm having an issue using the AsyncTypeahead from the react-bootstrap-typeahead project, where it seems like my onSearch handler is not getting called. I can see the typeahead on the page, but when I type in it, handleSearch is not being executed and I don't see any console logging. Here's a short example:
import React, {PropTypes, Component} from 'react';
import AsyncTypeahead from 'react-bootstrap-typeahead';
class CustomTypeahead extends Component {
state = { results: [] }
handleSearch(event) {
console.log("Show me what you got")
// fetch data here and set state to results in a promise
// this.setState(results)
}
render() {
return (
<div>
<AsyncTypeahead
onSearch={this.handleSearch.bind(this)}
options={this.state.results}/>
</div>
)
}
}
Any suggestions or insights are really appreciated!!!
Fixed by using:
import { AsyncTypeahead } from 'react-bootstrap-typeahead';
instead of
import AsyncTypeahead from 'react-bootstrap-typeahead';
and updating to version ^1.0.0 for react-bootstrap-typeahead

Categories

Resources