score:272
ES6 React.Component
doesn't auto bind methods to itself. You need to bind them yourself in constructor
. Like this:
constructor (props){
super(props);
this.state = {
loopActive: false,
shuffleActive: false,
};
this.onToggleLoop = this.onToggleLoop.bind(this);
}
score:0
If you call your created method in the lifecycle methods like componentDidMount... then you can only use the this.onToggleLoop = this.onToogleLoop.bind(this)
and the fat arrow function onToggleLoop = (event) => {...}
.
The normal approach of the declaration of a function in the constructor wont work because the lifecycle methods are called earlier.
score:0
In my case, for a stateless component that received the ref with forwardRef, I had to do what it is said here https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd
From this (onClick doesn't have access to the equivalent of 'this')
const Com = forwardRef((props, ref) => {
return <input ref={ref} onClick={() => {console.log(ref.current} } />
})
To this (it works)
const useCombinedRefs = (...refs) => {
const targetRef = React.useRef()
useEffect(() => {
refs.forEach(ref => {
if (!ref) return
if (typeof ref === 'function') ref(targetRef.current)
else ref.current = targetRef.current
})
}, [refs])
return targetRef
}
const Com = forwardRef((props, ref) => {
const innerRef = useRef()
const combinedRef = useCombinedRefs(ref, innerRef)
return <input ref={combinedRef } onClick={() => {console.log(combinedRef .current} } />
})
score:0
You can rewrite how your onToggleLoop method is called from your render() method.
render() {
var shuffleClassName = this.state.toggleActive ? "player-control-icon active" : "player-control-icon"
return (
<div className="player-controls">
<FontAwesome
className="player-control-icon"
name='refresh'
onClick={(event) => this.onToggleLoop(event)}
spin={this.state.loopActive}
/>
</div>
);
}
The React documentation shows this pattern in making calls to functions from expressions in attributes.
score:1
If you are using babel, you bind 'this' using ES7 bind operator https://babeljs.io/docs/en/babel-plugin-transform-function-bind#auto-self-binding
export default class SignupPage extends React.Component {
constructor(props) {
super(props);
}
handleSubmit(e) {
e.preventDefault();
const data = {
email: this.refs.email.value,
}
}
render() {
const {errors} = this.props;
return (
<div className="view-container registrations new">
<main>
<form id="sign_up_form" onSubmit={::this.handleSubmit}>
<div className="field">
<input ref="email" id="user_email" type="email" placeholder="Email" />
</div>
<div className="field">
<input ref="password" id="user_password" type="new-password" placeholder="Password" />
</div>
<button type="submit">Sign up</button>
</form>
</main>
</div>
)
}
}
score:2
in my case this was the solution = () => {}
methodName = (params) => {
//your code here with this.something
}
score:3
You should notice that this
depends on how function is invoked
ie: when a function is called as a method of an object, its this
is set to the object the method is called on.
this
is accessible in JSX context as your component object, so you can call your desired method inline as this
method.
If you just pass reference to function/method, it seems that react will invoke it as independent function.
onClick={this.onToggleLoop} // Here you just passing reference, React will invoke it as independent function and this will be undefined
onClick={()=>this.onToggleLoop()} // Here you invoking your desired function as method of this, and this in that function will be set to object from that function is called ie: your component object
score:12
I ran into a similar bind in a render function and ended up passing the context of this
in the following way:
{someList.map(function(listItem) {
// your code
}, this)}
I've also used:
{someList.map((listItem, index) =>
<div onClick={this.someFunction.bind(this, listItem)} />
)}
score:34
Write your function this way:
onToggleLoop = (event) => {
this.setState({loopActive: !this.state.loopActive})
this.props.onToggleLoop()
}
the binding for the keyword this is the same outside and inside the fat arrow function. This is different than functions declared with function, which can bind this to another object upon invocation. Maintaining the this binding is very convenient for operations like mapping: this.items.map(x => this.doSomethingWith(x)).
score:108
There are a couple of ways.
One is to add
this.onToggleLoop = this.onToggleLoop.bind(this);
in the constructor.
Another is arrow functions
onToggleLoop = (event) => {...}
.
And then there is onClick={this.onToggleLoop.bind(this)}
.
Source: stackoverflow.com
Related Query
- Using arrow functions inside React component does not transfer over parent context (which exists). this remains undefined in arrow function
- React setState inside of a function this is undefined
- React - this is undefined when binding function to component
- React TypeError: " this is undefined ", function inside function call not working
- React: "this" is undefined inside a component function
- React Hooks Error: Hooks can only be called inside the body of a function component
- React Warning: Cannot update a component from inside the function body of a different component
- Function inside functional component in React hooks - Performance
- React - stateless component, function inside or outside component
- Jest -- Mock a function called inside a React Component
- Mock React useRef or a function inside a functional component with enzyme and jest?
- React: 'this.state' is undefined inside a component function
- React: How to add onChange functionality inside of Function component using React Hooks? Need onClick event from a checkbox to influence input state
- React Native : Access Component state inside a static function
- React + Antd + Rollup Component Library "Error: Invalid hook call. Hooks can only be called inside of the body of a function component"
- React Hooks can only be called inside the body of a function component
- use of variable inside render function of react component
- React 17.0.1: Invalid hook call. Hooks can only be called inside of the body of a function component
- Receiving error - Hooks can only be called inside of the body of a function component when implementing React Spring basic example
- How to use React Context inside function of Class component
- export function inside react component or access state in same file outside of component
- react - conditional rendering inside component return function
- this.props shows as undefined in an arrow function within React Component
- I got an error for using React.useRef inside a react function component
- this.state is undefined inside function - React JS
- React Hooks Mobx: invalid hook call. Hooks can only be called inside of the body of a function component
- React Hooks - function inside function component passed as prop can't access state
- How does React Context work by using a function inside of a component
- how to set react parent component state by a async function and then pass this state to child as props?
- React router v4.2.2: using a string instead of function inside component prop of Route results in error
More Query from same tag
- Babel 6 react JSX transformer - disable strict
- How to display the saved Draft-JS data in the Editor? (React + Meteor)
- ReactJS - create script element
- Accessing basename of BrowseRouter
- Why is this counted as mutating state?
- Handling form clear and submit message on successful submission - React
- false positive in prop-types validation
- Heroku express + react + webpack - can't run on server
- React How to get Component to detect route change
- Why do I need to use array destructuring in function to re-render the component?
- How to display updated user values?
- How do I wait for 2 actions to dispatch another action
- React Application Update Data from DynamoDB Change
- Fixed Data Tables function onRowClick not returning row Data
- Is it against redux philosophy to copy redux state to local state?
- How can I display an HTML button using the return from a javascript function?
- Dynamic column and values in react table
- useState Hooks not working with enzyme mount()
- Render a react app in a non react web page
- React component state refactoring using ES7
- React: How to maintain caret position when editing contentEditable div?
- Rendering functional component from inside a functional component
- Import/Export sagas,containers,reducers
- React not updating component props?
- infinite scroll firing too quickly with cursor, but fine with space bar or scroll wheel
- Why my nextjs component is rendering twice?
- Can't set up beep sound in React.js
- How to determine if the current route is active in React
- Is there a way to render a custom react component for all paragraphs tags?
- How to avoid RegExp remove `u` in next.js