I'm trying to get hold of ref on children component but it doesn't seem to be working. The same approach works fine with the React class component but not with hooks.
import React, { useState, useRef } from "react";
export default function TestContainer(props) {
const ref = useRef(null);
return (
<div className="test-container" onClick={() => console.log(ref) // this logs null always}>
{React.Children.map(props.children, c =>
React.cloneElement(c, {
ref: n => {
console.log(n);
ref.current = n;
},
className: "test-container"
})
)}
</div>
);
}
export function Test(props) {
return <div className="test" {...props}>
{props.children}
</div>
}
Your component is okay. It is probably because the are no children rendered to that component. I reproduced it with using TestContainer in App and put <h2>Ref</h2> as a child of TestContainer:
(removed the comment of course, since it has been hiding the } )
App.js
import React from "react";
import "./styles.css";
import TestContainer from "./TestContainer";
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<TestContainer>
<h2>Ref</h2>
</TestContainer>
</div>
);
}
TestContainer.js
import React, { useState, useRef } from "react";
export default function TestContainer(props) {
const ref = useRef(null);
return (
<div className="test-container" onClick={() => console.log(ref)}>
{React.Children.map(props.children, c =>
React.cloneElement(c, {
ref: n => {
console.log(n);
ref.current = n;
},
className: "test-container"
})
)}
</div>
);
}
CodeSndbox:
HERE
Related
I am trying to use React Context successfully but I a have had a lot of trouble with it. I can't even successfully pass anything one level to the provider's immediate children, as a result all I am getting at this stage is "x is undefined" errors in the console. I am using a separate class for the context an a custom hook to manage my state data.
App.js (where TodoProvider component warps around its children) -
import logo from './logo.svg';
import './App.css';
import React, {createContext, useContext} from "react"
import TodoItem from './Components/Other/TodoItem';
import TodoList from './Components/List/TodoList';
import TodoAdd from './Components/Forms/TodoAdd';
import CompletedTaskList from './Components/List/CompletedTaskList';
import useTodo from './libs/useTodo';
import {TodoContext, TodoProvider} from "./Contexts/TodoContext"
function App() {
const {
todoArray, setTodoArray,
completedTaskArray,
addCompletedItem,
addTodoItem
} = useContext(TodoContext);
return (
<TodoProvider
value={
todoArray, setTodoArray,
completedTaskArray,
addCompletedItem,
addTodoItem
}
>
<div className="App">
<div className='card' id='mainCard'>
<div className='card-header' id='mainCardHeader'><h4>Todo List</h4></div>
<TodoList/>
<TodoAdd
/>
<CompletedTaskList
/>
</div>
</div>
</TodoProvider>
)
}
export default App;
TodoContext.js (My Context) -
import React, {createContext} from "react";
import useTodo from "../libs/useTodo";
const TodoContext = createContext();
const TodoProvider = ({children}) => {
const {
todoArray, setTodoArray,
completedTaskArray,
addCompletedItem,
addTodoItem
} = useTodo();
return (
<TodoContext.Provider
value={
todoArray, setTodoArray,
completedTaskArray,
addCompletedItem,
addTodoItem
}
>
{children}
</TodoContext.Provider>
)
}
export {TodoContext, TodoProvider}
useTodo.js (My custom hook to manage state)
import React, {useState} from "react"
const useTodo = () => {
const [todoArray, setTodoArray] = useState([{id: 1,todoTitle: "Code", todoDescription: "Practice React"},{id: 2,todoTitle: "Clean", todoDescription: "Wash dishes, wipe surfaces"}]);
const [completedTaskArray, setCompletedTaskArray] = useState(["Wake up", "Make Bed"]);
const [currentId, setCurrentId] = useState(3);
const addTodoItem = (todoTitleInputItem, todoDescriptionInputItem) => {
let todoTitle = todoTitleInputItem;
let todoDescription = todoDescriptionInputItem;
let id = currentId;
setCurrentId(currentId+1)
setTodoArray(todoArray => [...todoArray, {id,todoTitle, todoDescription}]);
}
const addCompletedItem = ({todoTitle}) => {
setCompletedTaskArray(completedTaskArray => [...completedTaskArray, todoTitle]);
}
return {
todoArray, setTodoArray,
completedTaskArray, setCompletedTaskArray,
addTodoItem,
addCompletedItem
}
}
export default useTodo;
CompletedTasklist(An example of my implementation of using a the context in one of it's children) -
import { useContext } from "react";
import {TodoContext, TodoProvider} from "../../Contexts/TodoContext"
const CompletedTaskList = () => {
const {
completedTaskArray
} = useContext(TodoContext);
return (
<div className="card todo-item">
<div className="card-header">
<h3> Completed Task</h3>
</div>
<div className="card-body">
<ul className="list-group ">
{completedTaskArray.map((item,index) => {
return <li className="list-group-item list-group-item-success" key={index}>{item}</li>
})}
</ul>
</div>
</div>
)
}
export default CompletedTaskList;
I've been trying to resolve this for a while now and cannot wrap my mind around it.
App.js
import React, { createContext, useContext } from 'react';
import CompletedTaskList from './comp';
import { TodoProvider } from './context';
function App() {
// you dont need useTodo, or TodoContext here
return (
<TodoProvider>
{/** todo Provider is a wrapper, you dont need to pass value as prop again, you are already doing it */}
<div className="App">
<div className="card" id="mainCard">
<div className="card-header" id="mainCardHeader">
<h4>Todo List</h4>
</div>
<CompletedTaskList />
</div>
</div>
</TodoProvider>
);
}
export default App;
Context
import React, { createContext } from 'react';
import useTodo from './useTodo';
// Define default values of your context data.
// otherwise everything would be undefined and you need to handle it everywhere
// you are using context
const TodoContext = createContext({
todoArray: [],
setTodoArray: () => {},
completedTaskArray: [],
addCompletedItem: () => {},
addTodoItem: () => {},
});
const TodoProvider = ({ children }) => {
const {
todoArray,
setTodoArray,
completedTaskArray,
addCompletedItem,
addTodoItem,
} = useTodo();
return (
<TodoContext.Provider
value={{
// <--- you were passing value incorrectly here, it should be an object
// you passed it as (......) instead of {...}
// curly braces not paranthesis
todoArray,
setTodoArray,
completedTaskArray,
addCompletedItem,
addTodoItem,
}}
>
{children}
</TodoContext.Provider>
);
};
export { TodoContext, TodoProvider };
Repasting the answer from the link i shared above.
I am generating my state in the parent component. latestFeed generates a series of posts from my backend:
import React, { useState, useEffect } from "react";
import { getLatestFeed } from "../services/axios";
import Childfrom "./Child";
const Parent= () => {
const [latestFeed, setLatestFeed] = useState("loading");
const [showComment, setShowComment] = useState(false);
useEffect(async () => {
const newLatestFeed = await getLatestFeed(page);
setLatestFeed(newLatestFeed);
}, []);
return (
<div className="dashboardWrapper">
<Child posts={latestFeed} showComment={showComment} handleComment={handleComment} />
</div>
);
};
export default Parent;
then latestFeed gets generated into a series of components that all need to hold their own state.
import React, { useState } from "react";
const RenderText = (post, showComment, handleComment) => {
return (
<div key={post._id} className="postWrapper">
<p>{post.title}</p>
<p>{post.body}</p>
<Comments id={post._id} showComment={showComment} handleComment={() => handleComment(post)} />
</div>
);
};
const Child= ({ posts, showComment, handleComment }) => {
return (
<div>
{posts.map((post) => {
return RenderText(post, showComment, handleComment);
})}
</div>
);
};
export default Child;
In its current form, the state of RenderText's is all set at the same time. I need each child of Child to hold its own state.
Thank you!
Instead of using RenderText as a function, call it as a component:
{posts.map((post) => (
<RenderText key={post.id} post={post} showComment={showComment} />
))}
This is because when used as a component, it will have it's own lifecycle and state. If used as a function call, React does not instantiate it the same way - no lifecycle, no state, no hooks, etc.
I'm currently coding a React -typescript App for practising FluentUI (a.k.a Fabric). Issue appears
with my App.tsx component.
import React, { useContext, useState } from 'react';
import logo from './logo.svg';
import './App.css';
import Search from './components/Search';
//import CategoriasProvider from './components/Context/CategoriasContext';
import Title from './components/Title';
import { ListGhostingExample } from '../src/components/DrinkList';
import { PrimaryButton } from 'office-ui-fabric-react';
import { CategoriasContext, ICategoriasContextInterface } from './components/Context/CategoriasContext';
import CategoriasProvider from './components/Context/CategoriasContext';
import axios from 'axios';
import './components/DrinkList.css'
import './components/Search.css'
interface IApp{
items:ICategoriasContextInterface[],
renderList:boolean
}
const App =()=> {
const contextValues=useContext(CategoriasContext);
return(
<CategoriasProvider>
<div className="App">
<div className="search">
<Search name={contextValues?.name} image={contextValues?.image} thumbnail={contextValues?.thumbnail} />
</div>
</div>
</CategoriasProvider>
);
}
export default App;
CategoriasProvider comes from a Context (CategoriasContext.tsx ). CategoriasProvider has the mentioned error Inside of CategoriasProvider there's a Search.tsx Component.Search's works as a "wrapper". Code is:
import React, { useEffect, useState } from 'react';
import { SearchBox,ISearchBoxStyles } from 'office-ui-fabric-react/lib/SearchBox';
import { PrimaryButton, IContextualMenuProps, Stack, IStackTokens, StackItem, initializeIcons } from 'office-ui-fabric-react';
import { ComboBox, DefaultPalette, Dropdown, DropdownMenuItemType, IComboBoxOption, IDropdownOption, IDropdownStyles, IStackItemStyles, SelectableOptionMenuItemType, Toggle } from '#fluentui/react';
import { getGlassesOriginal } from './Utils/Utils';
import axios from 'axios';
import '../Search.css';
import { CategoriasContext, ICategoriasContextInterface } from './Context/CategoriasContext';
initializeIcons();
const Search = (props:ICategoriasContextInterface) => {
//State
const [textContent, setTextContent] = useState("");
const [textBoxDisabled,disableTextBox]=useState(false);
const [comboBoxDisabled,disableComboBox]=useState(true);
const CategoriasContextInSearch=React.useContext(CategoriasContext);
const setTextContentInstate = (e: any) =>{
console.log("Contenido de e" + e.target.value);
setTextContent(e.target.value);
}
const showMessageInConsole = ():void => {
console.log(textContent);
setTextContent("");
}
// Example formatting
const stackTokens: IStackTokens = { childrenGap: 20 };
const searchBoxStyles: Partial<ISearchBoxStyles> = { root: { width: 200 } };
const dropdownStyles: Partial<IDropdownStyles> = {
dropdown: { width: 200 },
};
const options: IDropdownOption[] = [
{ key: 'glasses', text: 'Glasses', itemType: DropdownMenuItemType.Header },
];
function getGlasses () {
let outputArray:string[] = [];
console.log("getGlasses");
axios
.get("https://www.thecocktaildb.com/api/json/v1/1/list.php?g=list")
.then((response)=>{
let responseDataJson=response.data.drinks;
for (let element in responseDataJson) {
options.push({key:responseDataJson[element].strGlass,text:responseDataJson[element].strGlass});
}
}
)
return outputArray;
}
function selectSearch(){
if(textBoxDisabled){
disableTextBox(false);
disableComboBox(true);
} else {
disableTextBox(true);
disableComboBox(false);
};
}
useEffect(() => {
//TODO: No se debería llamar siempre a esta función. Solamente cuando se activa el sistmea de búsqueda (y además, cachearlo)
getGlasses()
});
return(
<div className="wrapper">
<div className="one"> <Toggle onClick={selectSearch}/></div>
<div className="two">
{
<SearchBox
name="searchBox"
className="searchBox"
styles={searchBoxStyles}
placeholder="Cheers!"
onChange={setTextContentInstate}
value={textContent}
disabled={textBoxDisabled}
/>
}
</div>
<div className="three">
<Dropdown
placeholder="Select a glass"
options={options}
styles={dropdownStyles}
disabled={comboBoxDisabled}
/>
</div>
<div className="four">
<div className="primaryButton">
<PrimaryButton text="Search" onClick={showMessageInConsole}/>
</div>
</div>
</div>
);
}
export default Search;
Hope you can help me!!! Thanks in advance!
The code which is causing the error in your title is in your comment. It's this line:
export const CategoriasProvider = () => {
You are defining CategoriasProvider as a component which takes no props. It can only accept IntrinsicAttributes which is basically just the key property.
But when you use CategoriasProvider in App you are calling it with JSX element children. You get an error because you have not said that the CategoriasProvider component can accept a children prop.
Any of the following types will solve your problem:
export const CategoriasProvider: React.FC = ({children}) => {
export const CategoriasProvider = ({children}: {children: React.ReactNode}) => {
export const CategoriasProvider = ({children}: React.PropsWithChildren<{}>) => {
Regardless, you'll want to pass the children down as children of the inner Provider component.
return (
<CategoriasContext.Provider value={hola}>
{children}
</CategoriasContext.Provider>
);
Your App component is not going to work as expected because the useContext hook which accesses the CategoriasContext is located outside of the CategoriasProvider. It will just get the default value for the context -- not the value from the provider.
You need to rearrange your components such that the hook call occurs in a component that is rendered inside of the CategoriasProvider.
Try this:
const Search = () => {
const contextValues = useContext(CategoriasContext);
return (
<div className="search">
<Search
name={contextValues?.name}
image={contextValues?.image}
thumbnail={contextValues?.thumbnail}
/>
</div>
);
};
const App = () => {
return (
<CategoriasProvider>
<div className="App">
<Search />
</div>
</CategoriasProvider>
);
};
export default App;
I'm trying to use React Context to update navbar title dynamically from other child components. I created NavbarContext.js as follows. I have wrapped AdminLayout with NavContext.Provider and use useContext in Course.js to dynamically update navbar title inside useEffect. However, when I'm doing this, react throws the following error on the screen.
Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
How can I use context properly so that I can update Header title from Course.js inside its useEffect?
NavbarContext.js
import React, {useState} from 'react'
export default () => {
const [name,setName] = useState("")
const NavContext = React.createContext({
name: "",
changeName: name => setName(name)
})
const NavProvider = NavContext.Provider
const NavConsumer = NavContext.Consumer
return NavContext
}
AdminLayout.js
<NavContext.Provider>
<div className={classes.wrapper}>
<Sidebar
routes={routes}
logoText={"Widubima"}
logo={logo}
image={image}
handleDrawerToggle={handleDrawerToggle}
open={mobileOpen}
color={color}
{...rest}
/>
<div className={classes.mainPanel} ref={mainPanel}>
<Navbar
routes={routes}
handleDrawerToggle={handleDrawerToggle}
{...rest}
/>
{/* On the /maps route we want the map to be on full screen - this is not possible if the content and conatiner classes are present because they have some paddings which would make the map smaller */}
{getRoute() ? (
<div className={classes.content}>
<div className={classes.container}>{switchRoutes}</div>
</div>
) : (
<div className={classes.map}>{switchRoutes}</div>
)}
</div>
</div>
</NavContext.Provider>
Navbar.js
import NavContext from "context/NavbarContext"
export default function Header(props) {
function makeBrand() {
var name;
props.routes.map(prop => {
if (window.location.href.indexOf(prop.layout + prop.path) !== -1) {
name = prop.name;
document.title = name;
}
return null;
});
return name;
}
return (
<AppBar className={classes.appBar + appBarClasses}>
<Toolbar className={classes.container}>
<div className={classes.flex}>
{/* Here we create navbar brand, based on route name */}
<NavContext.Consumer>
{({ name, setName }) => (
<Button
color="transparent"
href="#"
className={classes.title}
style={{ fontSize: "1.5em", marginLeft: "-2%" }}
>
{makeBrand() || name}
</Button>
)}
</NavContext.Consumer>
</Toolbar>
</AppBar>
);
}
Course.js
import React, { useState, useEffect, useContext } from "react";
import NavContext from "context/NavbarContext"
const AdminCourse = props => {
const context = useContext(NavContext);
useEffect(() => {
Axios.get('/courses/'+props.match.params.courseId).then(
res => {
context.changeName("hello")
}
).catch(err => {
console.log(err)
})
return () => {
setCourseId("");
};
});
return (
<GridContainer>
</GridContainer>
);
};
export default AdminCourse;
i think problem is there with your NavbarContext.js.
you are not exporting NavContext also.
you are defining provider, consumer but you are not using them either.
here's how you can solve your problem.
first create context and it's provider in a file as following.
NavContext.js
import React, { useState } from "react";
const NavContext = React.createContext();
const NavProvider = props => {
const [name, setName] = useState("");
let hookObject = {
name: name,
changeName: setName
};
return (
<NavContext.Provider value={hookObject}>
{props.children}
</NavContext.Provider>
);
};
export { NavProvider, NavContext };
in above code first i am creating context with empty value.
the i am creating NavProvider which actually contains value name as a state hook inside it.hookObject exposes state as per your naming conventions in code.
now i for testing purpose i defined two consumers.
one is where we update name in useEffect, that is ,
ConsumerThatUpdates.js
import React, { useContext, useEffect } from "react";
import { NavContext } from "./NavContext";
const ConsumerThatUpdates = () => {
const { changeName } = useContext(NavContext);
useEffect(() => {
changeName("NEW NAME");
}, [changeName]);
return <div>i update on my useeffect</div>;
};
export default ConsumerThatUpdates;
you can update useEffect as per your needs.
another is where we use the name,
ConsumerThatDisplays.js
import React, { useContext } from "react";
import { NavContext } from "./NavContext";
const ConsumerThatDisplays = () => {
const { name } = useContext(NavContext);
return <div>{name}</div>;
};
export default ConsumerThatDisplays;
and finally my App.js looks like this,
App.js
import React from "react";
import "./styles.css";
import { NavProvider } from "./NavContext";
import ConsumerThatDisplays from "./ConsumerThatDisplays";
import ConsumerThatUpdates from "./ConsumerThatUpdates";
export default function App() {
return (
<div className="App">
<NavProvider>
<ConsumerThatDisplays />
<ConsumerThatUpdates />
</NavProvider>
</div>
);
}
hope this helps!!
if you want to know more about how to use context effectively, i recooHow to use React Context effectively
I have read lot of answers here but all of them are tide to class components.
If I have simple functional component where I use useRef or createRef, ref.current is undefined
I'm assigning it on top of div or input but I can't get any of their properties
Console.log() gives me data only when I use standelone console.log(ref)
Every other property is undefined e.g. console.log(ref.current)
import React, { useRef } from "react";
import ReactDOM from "react-dom";
function App() {
const ref = useRef()
console.log(ref.current) // undefined
console.log(ref) // { current }
return (
<div className="App">
<h1 ref={ref}>Hello CodeSandbox</h1>
{/* <input ref={ref} name="test" value="bla" /> */}
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Take a look on this demo and look at console:
https://codesandbox.io/s/fervent-kirch-soe8n
But even in class component I can't access for example ref.current.innerHTML:
https://codesandbox.io/s/relaxed-beaver-ic1em
Ok I have found where is problem.
If I use useEffect() or if I use some button handler, I have access to element:
useEffect(()=>{
console.log(ref.current.innerHTML)
})
same in class component:
class App extends React.Component {
myRef = React.createRef();
componentDidMount(){
console.log(this.myRef.current); // correct
}
render() {
console.log(this.myRef.current); // null
return <h2 ref={this.myRef}>Start editing to see some magic happen!</h2>
}
}
or
<button onClick={()=> console.log(ref.current.innerHTML)}>Click</button>
You give the ref to the element in the dom,
so you can't access it before it actually gets render,
so in react that occur in the component lifecycle,
which is either useEffect or componentDidMount.
import React, { useRef, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const ref = useRef();
useEffect(() => {
console.log(ref.current)
},[])
return (
<div className="App">
<h1 ref={ref}>Hello CodeSandbox</h1>
{/* <input ref={ref} name="test" value="bla" /> */}
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
const Expander = forwardRef((_, ref) => {
return <div ref={ref}>test</div>;
});
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Way without ref and with ref and useState
import React, { useRef, useEffect, useState } from "react";
import ReactDOM from "react-dom";
function app() {
const ref = useRef('lalala');
const [h1Text, setH1Text] = useState('Hello CodeSandbox');
useEffect(() => {
console.log(ref.current)
});
const changeHeader = () =>{
setH1Text('mamamama');
}
const changeHeader2 = (ev) =>{
ev.target.innerHTML = "Hello CodeSandbox222222222222";
}
return (
<div className="App">
<h1 ref={ref} onClick={changeHeader}>{h1Text}</h1>
<h2 onClick={changeHeader2}>Hello CodeSandbox2</h2>
</div>
);
}
And code that input chagne the h1 without refs
function Example2() {
const [h1Text, setH1Text] = useState('Hello CodeSandbox');
const changeHeader = (ev) =>{
setH1Text(ev.target.value);
}
return (
<div className="App">
<h1>{h1Text}</h1>
<input onChange={changeHeader} name="test" />
</div>
);
}
If you referring component directly without mounting (componentDidMount/useEffect) then you will be get an undefined value. Alternatively you can use arrow function to access ref element.
example:
export function App(props) {
const ref = useRef()
console.log(ref.current) // undefined
const seeRef = () => {
console.log(ref.current) // <h1 ></h1>
}
return (
<div className='App'>
<h1 ref={ref}>Hello React.</h1>
<button onClick={()=> seeRef()}>Click</button>
</div>
);
}
Ref: https://stackoverflow.com/a/72548440/4652706