React Context consumer can't find props - reactjs

I'm trying to use React Context API to pass props, however I got "undefined" error. The version of react is 16.3.2, and react-dom version is 16.3.2. The following is my code:
Provider.jsx:
import React from 'react';
export const PathContext = React.createContext({
rootPath: "http://localhost/example"
});
App.jsx:
import React from 'react';
import {PathContext} from './Provider.jsx';
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<div>
<PathContext.Provider>
<AppRootPath />
</PathContext.Provider>
</div>
)
}
}
class AppRootPath extends React.Component {
render() {
return(
<div>
<span>App Root Path</span><br />
<PathContext.Consumer>
{
({rootPath}) => <span>{rootPath}</span>
}
</PathContext.Consumer>
</div>
)
}
}
export default App;
I can't find any problems in here, but the console reports this error: TypeError: Cannot read property 'rootPath' of undefined, and the error happens in here: ({rootPath}) => <span>{rootPath}</span>

About using a default value:
If there is no Provider for this context above, the value argument
will be equal to the defaultValue that was passed to createContext().
But you are wrapping it with Provider. Try removing Provider:
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return(
<div>
<AppRootPath />
</div>
)
}
}
class AppRootPath extends React.Component {
render() {
return(
<div>
<span>App Root Path</span><br />
<PathContext.Consumer>
{
({rootPath}) => <span>{rootPath}</span>
}
</PathContext.Consumer>
</div>
)
}
}

Related

TypeError: this.props.changeUser is not a function

I am new in React Js and want to call the parent method from the child method.
There is a class login.jsx when someone clicks on submits button then a method changeUser in FirstPage.jsx should be invoked but when I try the online solution I am getting same error again and again that this.props.changeUser is not a function.
Login.jsx (child class)
import React, { Component } from 'react';
class Login extends Component {
constructor(props){
super(props);
this.state ={
user : null
}
this.onNameChange = this.onNameChange.bind(this);
this.onHandleClick = this.onHandleClick.bind(this);
}
onNameChange = (event)=>{
this.setState({
user:event.target.value
})
}
onHandleClick=(event)=>{
event.preventDefault();
this.props.changeUser("hello");
}
render() {
return (
<form>
<h3>Sign In</h3>
<div>
<label>User Name</label>
<input type="text" name="userId" placeholder="Enter User name" onChange ={this.onNameChange}/>
</div>
<button className="btn btn-primary btn-block" onClick={this.onHandleClick}>Submit</button>
</form>
);
}
}
export default Login;
FirstPage.jsx (parent class)
import React, { Component } from 'react';
import Login from './Login';
class Firstpage extends Component {
constructor(props){
super(props);
this.state=
{
user:null
}
this.changeUser = this.changeUser.bind(this)
}
changeUser =(x)=>{
console.log(x)
}
render() {
return (
<div>
<Login changeUser ={this.changeUser}/>
</div>
);
}
}
export default Firstpage;import React, { Component } from 'react';
import Login from './Login';
class Firstpage extends Component {
constructor(props){
super(props);
this.state=
{
user:null
}
this.changeUser = this.changeUser.bind(this)
}
changeUser =(x)=>{
console.log(x)
}
render() {
return (
<div>
<Login changeUser ={this.changeUser}/>
</div>
);
}
}
export default Firstpage;
I am getting an error that TypeError: this.props.changeUser is not a function
Please help me.
try to avoid using a lambda expression within you class component. Just create a simple member function:
import React, { Component } from 'react';
import Login from './Login';
class Firstpage extends Component {
constructor(props){
super(props);
this.state=
{
user:null
}
this.changeUser = this.changeUser.bind(this)
}
changeUser(x) // Try to declare this as member function
{
console.log(x)
}
render() {
return (
<div>
<Login changeUser ={this.changeUser}/>
</div>
);
}
}
export default Firstpage
You are making a mistake here while binding , inside constructor
//WRONG
this.onNameChange = this.onNameChange.bind(this);
this.onHandleClick = this.onHandleClick.bind(this);
//RIGHT
this.onNameChange = onNameChange.bind(this);
this.onHandleClick = onHandleClick.bind(this);
CODE:
constructor(props){
super(props);
this.state ={
user : null
}
this.onNameChange = onNameChange.bind(this);
this.onHandleClick = onHandleClick.bind(this);
}

Why is Current always null for React.createRef() in react typescript

below is my code and console shows that current is always null and I am not sure why.
private tree: any;
constructor(props) {
super(props);
this.tree = React.createRef()
this.state = {
//
}
componentDidMount() {
console.log(this.tree);
}
render(){
return(
<div id= "tree" className="ba-treeview" ref={this.tree}>
//
</div>
)}
I think there are Syntax issues in your code.
I had tried it on CodeSandbox and it is working fine, though I had made correction to syntax wherever needed. Below is the code for your reference:
Tree Component:
import React from "react";
class Tree extends React.Component {
constructor(props) {
super(props);
this.tree = React.createRef();
this.state = {
someState: "StateValue"
};
}
componentDidMount() {
console.log(this.tree);
}
render() {
return (
<div id="tree" className="ba-treeview" ref={this.tree}>
TREE COMPONENT
</div>
);
}
}
export default Tree;
Usage (App.js):
import React from "react";
import "./styles.css";
import Tree from "./Tree";
export default function App() {
return (
<div className="App">
<Tree />
</div>
);
}
Below is the screen capture of execution for your reference:
Hope this may help.
Thanks

Using state in other components in React JS

I have three components.
export default class PermissionHandler extends React.Component {
constructor(props) {
super(props);
this.state = {
permission: true
}
}
}
export default class App extends React.Component {
render() {
return(
<PermissionHandler />
<Component1 />
)
}
}
export default class Component1 extends React.Component {
render() {
return(
<SomeComponent /* visible= true/false depends on permission */ />
)
}
}
I want PermissionHandler state to be used by any other components directly without using events or local state. Is it possible?
Can I use refs to achieve this goal?
export default class App extends React.Component {
constructor(props) {
super(props);
this.permissionHandler = React.createRef();
}
render() {
return(
<PermissionHandler ref={this.permissionHandler} />
<Component1 permissionHandler={this.permissionHandler}/>
<Component2 permissionHandler={this.permissionHandler} />
)
}
}
export default class Component1 extends React.Component {
render() {
return(
<SomeComponent visible={this.props.permissionHandler.currenct.state.permission} />
)
}
}
But Component1 doesnt rerender when the state of PermissionHandler updates
Simply move your state up the tree, to the App component

How to call a function in multilevel child component from parent component in Reactjs using class component

I have a requirement in which I have to call a function present in a child component from parent component using React.createRef() but the problem here is that it is multilevel child.
I'm able to call a function present in 'ChildComponent1' component but not able to call a function present in 'ChildComponent2' component from 'Parent' component. Please tell me a correct way to do this.
This is my parent.js file
import React, { Component } from 'react';
import ChildComponent1 from './ChildComponent1';
class ParentComponent extends Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
}
callFunctionFromChild = () => {
this.ref.current.doSomething()
}
render() {
return (
<div>
<ChildComponent1 ref={this.childRef} />
<button onClick={()=>{this.callFunctionFromChild()}}> Click Me <button>
</div>
);
}
}
export default ParentComponent;
This is my ChildComponent1.js file:
import React, { Component } from 'react';
import ChildComponent2 from './ChildComponent2';
class ChildComponent1 extends Component {
render() {
return (
<div>
<ChildComponent2 ref={this.props.ref} />
</div>
);
}
}
export default ChildComponent1;
and this is my inner ChildComponent2.js file:
import React, { Component } from 'react';
class ChildComponent2 extends Component {
doSomething = () => {
console.log("Something is done!!");
}
render() {
return (
<div>
My Child Component
</div>
);
}
}
export default ChildComponent2;

Using childrens in React Container

Can I use children in React Container or is it wrong?
For example, I have a list of buttons(ActionButton) that are grouped together (ActionMenu).
import React from 'react';
class App extends React.Component {
render() {
return (
<ActionMenu>
<ActionButton name="New" icon="add" />
<ActionButton name="Delete" icon="remove" />
</ActionMenu>
)
}
}
class ActionMenu extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
alert('Click!');
}
render() {
return React.Children.map(this.props.children, (button) =>
React.cloneElement(button, {
onClick: this.handleClick
})
);
}
}
function ActionButton({ name, icon, onClick }) {
return <button class={icon} onClick={onClick}>{name}</button>
}
You can use children regardless of whether it's a component of container.
"[children are] especially common for components like Sidebar or Dialog that represent generic 'boxes'."
In your case you have a menu, which falls into this category.
https://reactjs.org/docs/composition-vs-inheritance.html
I think this is what you are after. Actually you should just put the children in its closest parent instead of its grandpa.
import React from 'react';
import { render } from 'react-dom';
function ActionButton({ name, handleClick }) {
return <button onClick={handleClick}>{name}</button>
}
class ActionMenu extends React.Component {
constructor(props) {
super(props);
}
handleClick = () => {
alert('Click!');
}
render() {
return (
<div>
<ActionButton name="add" handleClick={this.handleClick}/>
<ActionButton name="remove" handleClick={this.handleClick} />
</div>
);
}
}
class App extends React.Component {
render() {
return (
<ActionMenu />
)
}
}
render(<App />, document.getElementById('root'));
You can try to run it in sandbox.
By the way, using bind is quite redundant now, we can use public class fields syntax, which is already ECMA stage 2.

Resources