React Context API can't bind 'this' - reactjs

When I type anything into the input which is inside of the <Input> component, I wanna execute the handleInput() function which is inside of the <MainProvider> component.
This (onChange={store.handleInput.bind(this)}) looks like working but it can't pass this.
In the console I just get undefined message.
Here's an example code.
const MainContext = React.createContext()
class MainProvider extends React.Component {
handleInput (e) {
console.log(e)
}
render () {
const store = {
handleInput: () => this.handleInput()
}
return (
<MainContext.Provider value={store}>
{this.props.children}
</MainContext.Provider>
)
}
}
class Input extends React.Component {
render () {
return (
<MainContext.Consumer>
{(store) => (
<input {...this.props} onChange={store.handleInput.bind(this)} />
)}
</MainContext.Consumer>
)
}
}
class App extends React.Component {
render () {
return (
<MainProvider>
<Input name='one' />
<Input name='two' />
</MainProvider>
)
}
}
How can I pass this in the onChange event? I'm using React 16.3.1.

The problem comes because you have used arrow function in MainProvider component which overrides the context being passed when you are calling function
render () {
const store = {
handleInput: () => this.handleInput() // using arrow function here overrides the contect
}
}
Change it to
class MainProvider extends React.Component {
handleInput (e) {
console.log(e)
}
render () {
const store = {
handleInput: this.handleInput
}
return (
<MainContext.Provider value={store}>
{this.props.children}
</MainContext.Provider>
)
}
}
However in this case you would explicitly need to bind from child components or it will take the context from where it is called.

Related

Pass original component's function to react HOC

I have created react HOC component as below.
const UpdatedComponent = (OriginalComponent) => {
class NewComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
counter:0
}
}
componentDidMount(){
}
incrementCount = () => {
this.setState(prevState => {
return {counter:prevState.counter+1}
})
}
render(){
return <OriginalComponent
incrementCount={this.incrementCount}
count={this.state.counter}
/>
}
}
return NewComponent
}
export default UpdatedComponent
and I am using that component in the below example
class HoverCounter extends Component {
componentDidMount(){
}
handleMessages = () => {
// need to do somthing
}
render() {
const {incrementCount, count} = this.props
return (
<div onMouseOver={incrementCount}>
Hoverd {count} times
</div>
)
}
}
export default UpdatedComponent(HoverCounter)
I want to know that is it possible to pass
handleMessages()
function to HOC?
like this
export default UpdatedComponent(HoverCounter,handleMessages)
I have no idea how to pass the original component function or props to HOC.
you could get everyThing in your Hoc like this :
const UpdatedComponent = (OriginalComponent , func) => {
componentDidMount(){
func()
}
in HoverCounter also you could add this changes:
static handleMessages(){
// need to do something
}
export default UpdatedComponent(HoverCounter , HoverCounter.handleMessages)

Reuse same DOM element in two different react components

I have a small question.
Let's imagine I have component A which holds , after component A does it's job I render component B. I would like that same DOM element (textarea) would be reused in component B.
The reason is if new textarea is rendered in component B it loses focus as it's just new DOM element. It's like after component A lifetame take textarea element from it and just put it in component B instead of rendering new one.
Sample APP
https://jsfiddle.net/remdex/v67gqyLa/1/#&togetherjs=aiRvTGhRK2
class AComponent extends React.Component {
render() {
return ( <textarea>A Component</textarea> )
}
}
class BComponent extends React.Component {
render() {
return ( <textarea>Should be A Component text</textarea> )
}
}
class ABComponent extends React.Component {
constructor(props) {
super(props)
this.state = {'component' : 'A'};
}
render() {
return (
<div><button onClick={(e) => this.setState({component:'B'})}>Switch to B Component</button>
{this.state.component == 'A' && <AComponent/>}
{this.state.component == 'B' && <BComponent/>}
</div>
)
}
}
ReactDOM.render(<ABComponent />, document.querySelector("#app"))
In your sandbox example, ComponentA and ComponentB are redundant. You can create ComponentA and ComponentB as a class if they are using same element and operate them with ComponentAB. You can change your ComponentAB like:
class A {
handle(input) {
// Do your A job here and return result
console.log("Handler A is running");
};
}
class B {
handle(input) {
// Do your B job here and return result
console.log("Handler B is running");
};
}
class ABComponent extends React.Component {
currentHandler = new A();
handleClick = () => {
this.currentHandler = new B();
};
handleChange = (event) => {
// Handle the input with current handler
var result = this.currentHandler.handle(event.target.value);
// If you want you can use result to cahnge something in view
// this.setState({value: result});
}
render() {
return (
<div>
<button onClick={this.handleClick}>
Switch to B Component
</button>
<textarea onChange={this.handleChange}>Text Area used between A class and B class</textarea>
</div>
)
}
}
I also edit the codebox example. You can find it here.
This can be achieved using a ref. ABComponent passes a ref to BComponent to attach to the textarea. When the state of ABComponent updates to component = 'B', then the ref is used to set focus. Use a ref passed to AComponent to grab its textarea value before it's unmounted, then set the value of the textarea in B to it.
import React, { Component, createRef } from "react";
...
class AComponent extends Component {
render() {
const { textareaRef } = this.props;
return <textarea ref={textareaRef} defaultValue="A Component" />;
}
}
class BComponent extends Component {
render() {
const { textareaRef } = this.props;
return <textarea ref={textareaRef} defaultValue="Should be A Component text" />;
}
}
class ABComponent extends Component {
state = { component: "A" };
refA = createRef();
refB = createRef();
componentDidUpdate(prevProps, prevState) {
const { component, content } = this.state;
if (prevState.component !== component) {
if (component === "B") {
this.refB.current.focus();
this.refB.current.value = content;
}
}
}
render() {
return (
<div>
<button
onClick={e =>
this.setState({ component: "B", content: this.refA.current.value })
}
>
Switch to B Component
</button>
{this.state.component === "A" && <AComponent textareaRef={this.refA} />}
{this.state.component === "B" && <BComponent textareaRef={this.refB} />}
</div>
);
}
}

Converting functional component to class component

I have one functional component, but as I need to use now state and more complex logic, I would like to convert it to class component.
But I don't know exactly how to get it working:
My functional component:
import React from 'react';
const FileList = (props) => {
const items = props.items.map((item) => {
return <p key={item.reqId} > { item.name }</ p>
});
return <div>{items}</div>
}
And I tried to do that:
export default class FileL extends React.Component {
constructor(props) {
super(props)
}
render() {
const { items } = this.props;
items = props.items.map((item) => {
return <p key={item.reqId} > {item.name}</ p>
});
return (
<div>{items}</div>
);
}
}
But this is not working.It says "items" is read-only.
I would like to keep the same functionality.
Any ideas?
In your render function
render() {
const { items } = this.props;
items = props.items.map((item) => {
return <p key={item.reqId} > {item.name}</ p>
});
return (
<div>{items}</div>
);
}
items is const so you can't override it. This has nothing to do with React. And you shouldn't reassign a props element, even if its defined with let. You might use the following:
render() {
const { items } = this.props;
return (
<div>
{
items.map((item) => <p key={item.reqId} > {item.name}</ p>)
}
</div>
);
}
You can try this,
export default class FileL extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
{
this.props.items.map((item) => {
return <p key={item.reqId} > {item.name}</ p>
})
}
</div>
);
}
}
Actually you don't need to convert your component to class based component, as React 16.8 comes with Hooks. Using Hooks you can do whatever you can do with class based component. They let you use state and other React features without writing a class.

Any better way to pass data from a child component to a function in a parent component without using bind()?

I'm using React.Context to pass a function down to child component which is inside another component. See figure down below.
I'm quite not comfortable using .bind() in order to pass the name variable to the function in the parent component.
Is there a better way to pass data from a child component to a function in a parent component without using .bind()?
See my code below:
import React, { Component, createContext } from 'react'
const AppContext = createContext()
class ComponentOne extends Component {
const handleClick = (name)=> {
alert(`Hello ${name}`)
}
render(){
return(
<AppContext.Provider
value={{
handleClick: this.handleClick
}}>
<p>Hello from ComponentOne</p>
</AppContext.Provider>
)
}
}
const ComponentThree = props=> {
const name = "lomse"
return(
<AppContext.Consumer>
(context=>(
<button onClick={context.handleClick.bind(null, name)}>Click me!</button>
))
</AppContext.Consumer>
)
}
You can always do:
const ComponentThree = props=> {
const name = "lomse"
return(
<AppContext.Consumer>
(context=> {
const handleClick = () => context.handleClick(name)
return <button onClick={handleClick}>Click me!</button>
})
</AppContext.Consumer>
)
}
What you're doing is about binding arguments so when a function is called later it will be called with those arguments. It has nothing to do with React Context.
and onClick needs to be a function, that will be called - well - on click.
Or you could do:
const handleClick = (name) => () => {
alert(`Hello ${name}`)
}
and then:
const ComponentThree = props=> {
const name = "lomse"
return(
<AppContext.Consumer>
(context=> (
<button onClick={context.handleClick(name)}>Click me!</button>
))
</AppContext.Consumer>
)
}

function argument in component's constructor in react.js

When I look at the following line in this example:
const SortableItem = SortableElement(({value}) => <li>{value}</li>);
then I don't understand where is the lambda function ({value}) => <li>{value}</li> used in SortableElement ?
Can someone please enlighten me ?
SortableElement's code:
import React, {Component, PropTypes} from 'react';
import {findDOMNode} from 'react-dom';
import invariant from 'invariant';
// Export Higher Order Sortable Element Component
export default function SortableElement (WrappedComponent, config = {withRef: false}) {
return class extends Component {
static displayName = (WrappedComponent.displayName) ? `SortableElement(${WrappedComponent.displayName})` : 'SortableElement';
static WrappedComponent = WrappedComponent;
static contextTypes = {
manager: PropTypes.object.isRequired
};
static propTypes = {
index: PropTypes.number.isRequired,
collection: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
disabled: PropTypes.bool
};
static defaultProps = {
collection: 0
};
componentDidMount() {
let {collection, disabled, index} = this.props;
if (!disabled) {
this.setDraggable(collection, index);
}
}
componentWillReceiveProps(nextProps) {
const {index} = this.props;
if (index !== nextProps.index && this.node) {
this.node.sortableInfo.index = nextProps.index;
}
if (this.props.disabled !== nextProps.disabled)
{
let {collection, disabled, index} = nextProps;
if (disabled) {
this.removeDraggable(collection);
}
else {
this.setDraggable(collection, index);
}
}
}
componentWillUnmount() {
let {collection, disabled} = this.props;
if (!disabled) this.removeDraggable(collection);
}
setDraggable(collection, index){
let node = this.node = findDOMNode(this);
node.sortableInfo = {index, collection};
this.ref = {node};
this.context.manager.add(collection, this.ref);
}
removeDraggable(collection) {
this.context.manager.remove(collection, this.ref);
}
getWrappedInstance() {
invariant(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableElement() call');
return this.refs.wrappedInstance;
}
render() {
const ref = (config.withRef) ? 'wrappedInstance' : null;
return (
<WrappedComponent ref={ref} {...this.props} />
);
}
}
}
export default function SortableElement (WrappedComponent, config = {withRef: false}) {
return class extends Component {
...
render() {
const ref = (config.withRef) ? 'wrappedInstance' : null;
return (
<WrappedComponent ref={ref} {...this.props} />
);
}
}
}
Look at the render() method in the returned React Component by the higher order SortableElement function, the lambda function (which is a stateless component) is passed as the first argument to the higher order function, and this first argument is going to end up as being the parameter WrappedComponent you see in the signature of this higher order function.
So this higher order function is going to spit a React component with a render() method that uses/calls your actual React component that you just passed in (the lambda function).
<WrappedComponent ref={ref} {...this.props} />
Thanks to ({value}) => <li>{value}</li> in
const SortableItem = SortableElement(({value}) => <li>{value}</li>);
we will be actually rendering an li element with a value passed as a prop from the map method below.
const SortableList = SortableContainer(({items}) => {
return (
<ul>
{items.map((value, index) =>
<SortableItem key={`item-${index}`} index={index} value={value} />
)}
</ul>
);
});
In the context of the SortableElement's API code the important thing is that it renders the WrappedComponent (lines 67-69). We can treat SortableElement as any other Higher Order Component - a component that wraps another component to deliver some extra functionality. In this case - a fancy sorting animation of the lambda function.
Put simply
({value}) => <li>{value}</li> is a short hand for
React.crateClass({
render:function(){
return <li>{this.props.value}</li>
}
})
refer to pure functional component in React
and SortableElement is a higher order component wrapping another React component ,such the functional component above

Resources