setValue is not defined in react for react hooks - reactjs

I'm getting an error saying the setValue portion of my code is not defined, but I did in the bottom portion of my main function. Not sure what's going on.
import React, {useState} from "react";
const updateAPI = () => {
setValue("test");
}
export default function App() {
const [value, setValue] = useState("");
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={updateAPI}></button>
<p>{value}</p>
</div>
);
}

Restructure code as below and try,
import React, {useState} from "react";
export default function App() {
const updateAPI = () => {
setValue("test");
}
const [value, setValue] = useState("");
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={updateAPI}>HI</button>
<p>{value}</p>
</div>
);
}

your updateAPI function cant find setValue useState hook because they are not in the same scope.
import React, {useState} from "react";
export default function App() {
const [value, setValue] = useState("");
const updateAPI = () => {
setValue("test");
}
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<button onClick={updateAPI}></button>
<p>{value}</p>
</div>
);
}

Related

Why my useContext is not working in my code

I have just started learning useContext hook and I am struck in this problem.
I am not able use the hook itself when I am trying to print that in console its says undefined.
This is the App.js
import "./styles.css";
import NoteState from "./Context/Notes/NoteState";
import About from "./components/About";
export default function App() {
return (
<>
<About />
<div>ankit</div>
<NoteState>
<About />
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
</NoteState>
</>
);
}
These are the files where the hook is defined
import { createContext } from "react";
const noteContext = createContext();
export default noteContext;
Second one is
import React from "react";
import NoteContext from "./NoteContext";
const NoteState = (props) => {
const state = {
name: "Name",
surname: "Surname"
};
return (
<>
<NoteContext.Provider value={state}>
{props.childern}
</NoteContext.Provider>
</>
);
};
export default NoteState;
I am trying to use this in About.jsx
import React from "react";
import noteContext from "../Context/Notes/NoteContext";
import { useContext } from "react";
const About = () => {
const a = useContext(noteContext);
console.log(a); - >> comes undefined
return (
<>
{/* <div>this is about note me but {a.name}</div> */} this gives error
</>
);
};
export default About;
You can see the same in this codesand box link.
link
There seems to be a typo in your NoteState component. It should be props.children and not childern. When I made that change and ran your sandbox, it was working fine.
Try to wrap the all application into NoteContext:
import NoteContext from './NoteContext';
export default function App() {
return (
<>
<NoteContext.Provider value={state}>
<About />
<div>ankit</div>
<NoteState>
<About />
<div className='App'>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
</NoteState>
</NoteContext.Provider>
</>
);
}

Implementing The SliderPicker from react-color library

I can't find a proper example on how to implement the SliderPicker as a functional component, any suggestions?
import React,{useState} from "react";
import "../Styles/Pixel-editor.scss"
import { HuePicker,SliderPicker } from 'react-color';
function App(){
return(<div className="App"><SliderPicker/> </div>);
}
You need a state with object, which has a hex property. Then you can set it with onChangeComplete property:
const [color, setColor] = React.useState({ hex: "#FFFFFF" });
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<SliderPicker
color={color}
onChangeComplete={(color) => setColor(color)}
/>
</div>
);
https://codesandbox.io/s/polished-resonance-5il68w

How to declare `async` functional component in react?

I am trying to load the image in typescript. but not works. what is the correct way?
Here is my code:
import "./styles.css";
import React, { FC } from "react";
type ImageLoad = (subString: string) => Promise<boolean>;
const App: FC = async () => {
const imgsource: ImageLoad = await import("https://picsum.photos/200/300");
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<img src={imgsource} />
</div>
);
};
export default App;
CodeSandbox:
No async code is needed in your example. Because you already have the URL of the image, all you need to do is set the image's src attribute:
const App: FC = () => {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<img src="https://picsum.photos/200/300" />
</div>
);
};

How to return a component and a function, or what's the alternative?

[React] What is the "way" to send/share a function between components?
Better explained in (useless) code
Here I have no problem since everything is in the same component (https://codesandbox.io/s/compassionate-ishizaka-uzlik)
import React, { useState } from "react";
export default function App() {
const [bookmarks, setBookmarks] = useState();
const letbook = () => setBookmarks("hello");
const Card = () => <div onClick={letbook}>hey</div>;
const MyCom = () => {
return <div><Card /></div>;
};
return (
<div className="App">
<h1 onClick={letbook}>Hello CodeSandbox</h1>
<MyCom />
<div>{bookmarks}</div>
</div>
);
}
But then, if now I want to split code, how do I do this? The problem is how to share letbook (this code doesn't work)
import React, { useState } from "react";
export default function App() {
const Card = () => <div onClick={letbook}>hey</div>;
return (
<div className="App">
<h1 onClick={letbook}>Hello CodeSandbox</h1>
<MyCom />
<div>{bookmarks}</div>
</div>
);
}
const MyCom = () => {
const [bookmarks, setBookmarks] = useState();
const letbook = () => setBookmarks("hello");
return (
<div>
<Card />
</div>
);
};
I could use a hook that returned the component and the function
const [letbook, MyCom] = useMyCom
But this is not recommended (https://www.reddit.com/r/reactjs/comments/9yq1l8/how_do_you_feel_about_a_hook_returning_components/)
Then I can use a hook and a component, as with the following code, but the code itself seems obfuscated to me, to a point that I doubt whether I should split the code or not
Unless (and this is the question) whether there is a smarter way to do this
import React, { useState } from "react";
export default function App() {
const [bookmarks, setBookmarks, letbook] = useMyCom();
return (
<div className="App">
<h1 onClick={letbook}>Hello CodeSandbox</h1>
<MyCom card={props => <Card letbook={letbook} />} />
<div>{bookmarks}</div>
</div>
);
}
const Card = ({letbook}) => <div onClick={letbook}>hey</div>;
const useMyCom = () => {
const [bookmarks, setBookmarks] = useState();
const letbook = () => setBookmarks("hello");
return [bookmarks, setBookmarks, letbook];
};
const MyCom = ({ letbook, card }) => <div>{card(letbook)}</div>;
Split your component to reuse it is definitely a good idea. But make sure your are using and manipulate a single state in the same file an pass it as props. Also, it is important that you avoid to re-render your child component. Only when your main component change props that are necessary to re-render your child component.
import React, { useState, memo } from "react";
const MyCom = memo(props => {
return <div>{props.bookmarks}</div>;
});
export default function App() {
const [bookmarks, setBookmarks] = useState();
const letbook = () => setBookmarks("hello");
return (
<div className="App">
<h1 onClick={letbook}>Hello CodeSandbox</h1>
<MyCom bookmarks={bookmarks} />
</div>
);
}

userRef or createRef returning undefined in functional component

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

Resources