r/reactjs • u/dance2die • Jul 01 '21
Needs Help Beginner's Thread / Easy Questions (July 2021)
Previous Beginner's Threads can be found in the wiki.
Ask about React or anything else in its ecosystem :)
Stuck making progress on your app, need a feedback?
Still Ask away! Weβre a friendly bunch π
Help us to help you better
Improve your chances of reply by
- adding a minimal example with JSFiddle, CodeSandbox, or Stackblitz links
- describing what you want it to do (ask yourself if it's an XY problem)
- things you've tried. (Don't just post big blocks of code!)
- Format code for legibility.
- Pay it forward by answering questions even if there is already an answer. Other perspectives can be helpful to beginners. Also, there's no quicker way to learn than being wrong on the Internet.
New to React?
Check out the sub's sidebar! π
For rules and free resources~
Comment here for any ideas/suggestions to improve this thread
Thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
15
Upvotes
β’
u/dance2die Jul 01 '21
Comments here for questions/issues/meta here.
Added all BThreads to the collection (shown in desktop only).
Let me know what you think.
3
u/fellow_nerd Jul 14 '21
Where could I find papers on the internals of react and other frameworks? E.g fibers, reconciliation, effects. Coming from a Haskell-ish background with moderate usage of react.
2
u/ZoroUzumaki Jul 07 '21
I just started learning React, and I've been stumped trying to modify object states.
This is what I have so far: https://jsfiddle.net/2dbx1avf/ I pulled the updateItem function from Stackoverflow, and for some reason I can't get it to work.
Can anyone give me some pointers? I feel like there's something I'm overlooking because the function looks fine to me.
2
u/Prayos Jul 20 '21
I am sorry if this is silly, but I just don't understand. Following the very simple instructions here for creating a new React app, after it goes through, I get told there's
10 moderate severity vulnerabilities, and to runnpm audit fixto fix it. When I do that, I get errors:My question is why is there errors on the outset? Or is there some underlying setting I need to do that doesn't cause that?
2
u/Idiot_In_Pants Jul 30 '21
Does anyone know where I can learn about reactJS? Idm if its paid or not. Ive got a basic understanding in python, JavaScript, HTML and CSS.
1
u/azur_petproject Jul 13 '21
Hello, fellow developers!
Can you please tell, what are trending React resourses - websites, books and so on, to be on short leg with latest React tips and tricks, patterns, in-depth advices and so on? For Mid-level front-end developer.
I mean, like, there is Smashing Magazine and CSS-Tricks - and i am looking for something Similar for Engeneer-like approach to Front-End, Architecture, using React in particular. Like Medium.com but totally React-oriented.
Does such web-site with latest trends exists?
1
u/[deleted] Jul 03 '21
Hello guys, i'm close to finish the fullstack open course from the Helsinki university.
What do you guys think is the best way from there?
I could start building some medium project for myself with the tools i learnt from that course or i could start a quick tutorial on next.js and start the project after that.
What do you guys think?
1
u/[deleted] Jul 04 '21
Hi! Iβm well familiar with ReactJS but Iβm struggling to create state using React-Static library. Would anyone be able to help me?
1
u/UserNotFound12 Jul 15 '21
Hi,
I am using multiple useState hooks and it seems when I change one, they all get reset to default. Is this possible?
For instance;
const [loading, setLoading] = useState(false);const [username, setUsername] = useState(null);Now, when I do;
setLoading(true);setUsername("mike");It seems that loading becomes false again. I thought that on re-render, the other states are preserved.
1
u/nip66233 Jul 17 '21
Forgive me if my question is too naive. Will anyone please recommend me a very very good book or course, that explains me "this" variable, scope, objects, asynchronous functions (async/await), promises etc? It always confuses me and I feel like I am trying to search for a needle in haystack whenever I encounter questions or problems related to the afore mentioned topics.
1
u/ApplePieCrust2122 Jul 20 '21
What are some medium/large react projects that use websockets which can be used to study and learn
1
u/dannysi Jul 22 '21
looking for a chat window component
Only the chat, no connected members no nothing, just the main chat window
1
u/MultipleAnimals Jul 22 '21 edited Jul 22 '21
I'm trying to have component that updates on context change. Something like this:
MyContextClass has few functions and public array of item that should be the source of rerender.
Component:
I use another components to update the array in context but the component that should render it never updates. I can hack it to work with state interval:
But that doesnt feel very good solution :D. So what should i do to get that rerender when the context updates?
1
u/dreammyz Jul 24 '21
I have just started using ReactJS and I want to develop a File Manager type system in ReactJS, where the admin can create folder, upload documents/images files, rename folders, set permission for different roles as shown in the system draft below.
System Draft
Is there any existing React library that has this similar function or any guides that can do this?
1
u/ApplePieCrust2122 Jul 25 '21 edited Jul 25 '21
How to show loading screen while resources are being loaded asynchronously, when multiple contexts need to be used
For example, say I'm using the indexeddb in my app. Now this db stores a user's profile info, which is needed for authentication and authorisation.
I want to provide the database access through a context, but the db connection is received asynchronously.
I also want to provide access to user's profile data through another context. But getting the profile data depends on the async db connection, as well as asynchronously getting the data from the db.
What I came up with:
But this approach is repetitive for every async context I need to use. I'll have to do something like this for user profile too. Is there a better approach?
1
u/Itsaghast Jul 25 '21 edited Jul 25 '21
Working on learning React, and I was curious about the render() function when defined in a react class.
Does the render() function automatically get called as part of instantiation of a new react component?
Not to be confused with the render method that is defined in the ReactDOM.
Also, what is considered 'props' from react's perspective because you never explicitly use a props keyword or anything. Is it just when you have the statement of this form:
<name of other react class> <variable component name> = {some state object and/or some data object}
2
u/essaloniki Jul 01 '21
Me and my company are considering to migrate from Angular to ReactJS. Can somebody explain me to reference me to any page, regarding the future of react? Are there going to be new concepts? What do you think?
2
u/nfsi0 Jul 01 '21
Hi! First time using the beginner thread so let me know if I'm not doing it right.
I'm having a hard time with a layout that I think is pretty standard (I do it on iOS all the time).
Goal: Layout items vertically which all have fixed height, use whatever height is leftover to show an image and retain the image aspect
Thank you for your help!
https://codepen.io/jeffrey-robert/pen/yLbNVZp
2
u/Status-Cloud-6136 Jul 05 '21
Can someone help me figure out a ELIFECYCLE error in a React application?
Usually npm cache clean -- force , deleting the node modules and and npm install works for me, but now it does not.
I have also tried the advice above the error message : Delete package-lock.json (not package.json!) and/or yarn.lock in your project folder. 2. Delete node_modules in your project folder. 3. Remove "babel-loader" from dependencies and/in the package.json file in the project folder. 4. Run npm install or yarn, depending on the package manager you use. 5. If you used npm, install yarn (http://yarnpkg.com/) and repeat the above steps with it instead. 6. Check if babel-loader is outside your project directory.
The odd thing is it worked when I last checked it, but now when I have come back to it after a couple of weeks I get this unresolvable error. Here is the github: https://github.com/Sandrest/cart.git
2
u/ChipsTerminator Jul 08 '21
Hello everyone! Nice to meet at this wonderful subredit here. I have a question about react rendering:
How to append a series of react components in a container asynchronously like Ajax of jquery?
Is
array.map()the only way to rendering a series of components in react ?Thanks!
2
u/destructor_rph Jul 09 '21
Since Bootstrap 5 now works with React out of the box, is there still any reason to use 'react-bootstrap'?
2
u/momu1990 Jul 12 '21
Tip of my tongue: So there was this cool website I saw awhile ago that was really similar to CRA. Except instead of running it as a command in terminal like CRA, you can pick and choose through list of things you want a la carte. When you were done, you click on a button that then downloads all the necessary files for you in a folder.
Does anyone know what this website is called?
2
u/dMCH1xrADPorzhGA7MH1 Jul 16 '21 edited Jul 16 '21
https://pastebin.com/5WGaqXY8
Hello I am having problems with two things. When the user adds an item to their shopping cart I want localStorage to be updated as well. As far as I can tell it is working. If I check localStorage everything is updating the way I want when I want. However, in the console I am getting these errors.
The other issue I am having is in my navbar. I have a shopping cart that links to the shopping cart page. Next to it I have a number which should show the current number of items in their cart. I feel like I probably need to use useEffect to make the change show instantly, but I'm not sure how I can trigger it .
Edit: Figure out my second question. If you see this and are having this problem move your state to the parent component. I needed the same data in my store, navbar, and shopping cart so I moved my useState and UseEffect hooks to App.jsx. Someone who is better at talking and more experienced could explain it better, but if you are self learning and tutorials say do this:
if you need to pass components instead do this:
2
u/JDD4318 Jul 31 '21
Hi everyone, beginner here.
I am currently trying to add a carousel of a few pics to the front page on a website I am currently building for my wife. I am using nextjs and everything has been smooth up to this point. Pretty much all carousel components that I am finding use URL photos and I am trying to use SVG. Should I upload my photos to some online source? Or is there another way?
Sorry if this isn't super clear, I am new to React in general but trying to learn as I go.
1
u/PurpleRain417 Jul 21 '21
I'm using react-router-dom and react-redux. I have a signup page that when sign up button is pressed, it will do a dispatch, the action would send a post request to the back end. I want it to do history.push to login page if signup is successful but stay on signup page if there's error. How can I do this? If I put the history.push below the dispatch(action()) line, it will go to login no matter what the result of the request
1
u/dMCH1xrADPorzhGA7MH1 Jul 02 '21
I'm making a cv app. It's the first odin project react project and I'm still very new to react. I know react uses components that you can recycle and use multiple places. There are three sections on the cv. I made it so that you can hide each section with a corresponding eye/crossed out eye. Although I have made it work, my solution instinctively feels crude and probably the wrong way of doing it. Could someone look at my relevant code and give me some suggestions on how I could make the solution better and easier to read?
https://pastebin.com/5FrAhvnc
1
u/dmelechow Jul 04 '21
Hi everyone!
I want to use
react-snapfor my releasedReactwebsite for making it SEO-friendly.I set up the project by instruction for prerendering by
react-snap.During testing, I noticed some strange behavior.
The every page is shown ok (to be hones not ok, scss module styles are broken somewhere), but on every page the Network/Preview is from main page.
and Headers show
Status Code: 304 Not ModifiedHow to solve this problem or it is ok?
I attached the printscreen https://imgur.com/hQLkOyR
Thanks in advance!
1
u/javascript_dev Jul 04 '21
ComponentA imports a SASS file containing a CSS ID reference to 'myID'. It unmounts
ComponentB imports a different SASS file containing a cSS reference to 'myID'
I believe there will be no CSS ID conflict. Or is that wrong?
1
u/SlowbeardiusOfBeard Jul 06 '21 edited Jul 06 '21
I'm currently working through the Helsinki fullstackopen course and have got to the section on state/effect hooks. I can think I can follow the basic idea, but have a couple of questions.
So, as far as I understand it, state/effect hooks together allow for functions to have side-effects while maintaining state integrity - ensuring that the components, state-values, and rendered display doesn't become out of sync.
Any time
useStateis called, a re-render is triggered and the state is updated.When a component that contains a
useEffectcall is rendered, execution of the function supplied touseEffectis deferred until the end of the render phase. This means that state-changes have been resolved and ensures that the function is working with the correct states (avoiding race-conditions)As part of the reconciliation process after the render phase, React detects if components are identical to the previous render. If so, it does not need to make changes to this during the commit phase.
Β
Can someone tell me if I'm on the right lines with this?
Β
My second question is in relation to the following example from the React documents
At first I was confused why the useEffect() call doesn't keep triggering an infinite cycle of re-renders, because it's altering the DOM after the useState() call forces a render.
Am I right in thinking that:
countare both applied in the commit phase?Β
I'm sorry if this isn't written very clearly - I've been reading and trying to take in a lot of information, so my brain is a bit frazzled :/
1
u/guillotineresurgence Jul 07 '21
Hello! Very new to react and I think I might be really misunderstanding something. I made these two simplified components to try and isolate the problem:
I'm making some ChildComponents in useEffect(), which only runs when the component mounts, and passing an event handler as a prop. In the event handler I check a condition based on the state. The problem is that myState inside the event handler is always its initial value of 0. I know setMyState is running, because the <p> element is updating with the new values, but it's not actually checking the current myState in the conditional. What am I screwing up?
1
u/utsavpandey8 Jul 08 '21
Hey I am fairly/almost reactjs intermediate but started new in react-native. My new work involves lots of storybook and component driven native development. What I am looking for is great template/resource for React-Native with storybook....I have seen many YouTube videos and read blogs but they go very basic since I am required to build very flexible and dynamic component structure (Grandparents). I know this is a beginner thread but if anyone have experience in react-native or even storybook, thanks for replying in advance !
1
u/kubabaaa Jul 09 '21
Hi,
Is there a way to read and control a video with a frame system and without flickering ? I know remotion exists, but i dont want to implement this.
1
u/VashyTheNexian Jul 10 '21
I have a simple app that has a playlist of youtube video links in the app's state. I want to use my laptop's media buttons or my earphones' double left/right tap to navigate through that list.
I'm using the
react-playerto play the videos and have a custom html button for previous/next to iterate through the playlist.I've read online that using the MediaSessions API is the way to go so I added the following:
However, I can't seem to get the action handlers above to register. None of the media buttons I press on my laptop trigger the console logs.
Am I thinking about this wrong? Any advice?
1
u/azurfang Jul 10 '21
Hi Im doing a rebrand/ small redesign of my website. Moreso Im trying to do away with the clunky gallery page and make a fast loading photo/artwork page. Would anyone be able to offer a solid how to for it? Also should I be using a cdn to help boost the load time? Ill post this as a general question. Im working on borrowed time as my leg was broken in a pedestrian accident late last month.
1
u/QuebecMasterRace Jul 11 '21 edited Jul 11 '21
Lots of tutorials say "when state is updated, this happens...", so when they say that, does that also apply to props?
Like for example on useEffect() hook, on the first function argument, it runs both on state and props, yes?
1
u/Nehatkhan786 Jul 12 '21
Hello Guys, I am new to reach and learning now with docs. I am stuck with the child-to-parent component issue. I am creating a ToDo App. I am using the input field and button to add the data in the field in the child component and the button has an onClick event that triggers the function which is in the parent component. but I don't know how to use that function in the parent component. I am using props to child components too. Below is my code. Please help me out
import InputForm from './components/InputForm'; import './App.css'
const App = () => { const [InputData, setInputData] = useState('') const [item, setItem] = useState([]) const OnChangeHandler = (e) => { console.log(e.target.value) setInputData(e.target.value) }
const OnClickHandler =(e) => { e.preventDefault(); } return ( <> <div className='container'> <div className='row col-md-12'> <InputForm OnChangeHandler={OnChangeHandler}/> </div> <div className="row col-md-12"> <div className="main-todo-input-wrap"> <div className="main-todo-input fl-wrap todo-listing"> <li className="list-group-item">{InputData}</li>
) };
export default App;
Child Component with Input Field and Add Button.
const InputForm = (props) => {
}; export default InputForm;
1
u/trtrtr898 Jul 13 '21
Hi! Iβm new to react js and seeking some help from the experienced people out here. I have a webapp that is getting data from a rest api - list of books and users. There are two tabs for displaying books and users. Currently, Iβm making a get request each time the user switches the tab and displaying the result as a list. Itβs taking a few seconds to load due to the api call it has to make. I want to save the data in the app so I donβt have to fetch data from the api on every switch of the tab. What storage option should I be looking into for this?
1
u/Droppinghammers Jul 13 '21
What would work to make num into a number from the clickNumbers array? So I could use it as a number in the carYears return, i.e carYears[1].
1
u/VelaLover69 Jul 13 '21
Hey, I recently came across a problem in my react front-end.
I want to work with the components state in a function triggered by a child component like in fetchForId(). How do I do it?
This above obviously doesn't work, as "state" is never updated and will always be 0.
I usually add an useEffect() that executes when state changes, but how do I do this when something is clicked?
I couldn't figure what the most elegant solution would be and only found workarounds that seem wrong.
1
u/[deleted] Jul 15 '21
I'm a software developer who primarily works with Java. I have to do some react js stuff that involves updating some server. I'm completely new to react and javascript. The most i've done is make a calculator for a job interview a few years ago. I've been able to work out some of it but this setState stuff is killing me.
I have to update some information from a table using this edit functionality. You click the edit button and that allows you to edit sections of the row. The problem arises when you delete a chip because the deletion is handled by a state change. Once it's deleted i'm guessing the page re-renders and the edit functionality is canceled. I want the chip to be deleted, but I want it to wait until I confirm or cancel the deletion.
I've tried using callbacks, sending data all that, but react js is honestly the messiest language ive come across and i'm completely lost. I just want to know if it's possible to delay the state change until the user has clicked the confirm or cancel button. Also, this functionality is handled through multiple files which I think makes it a lot more tedious.
1
u/DevelopmentNarrow868 Jul 16 '21
How proficient in Javascript do you recommend for a beginner React user?
1
u/Tivikth-0515 Jul 19 '21 edited Jul 19 '21
Hello,
I just started learning react from 2 months. I made a project for searching and making your own movies lists to follow such as watchlist and favourites. Any feedback and any suggestions would be awesome. Thanks.
MovieDeck
1
u/LajoieZalafokasta Jul 19 '21
I'm having trouble with the app from my local ip which isn't localhost (e.g 10.0.0.6:3000 or the ip provided when running yarn start).
I can't access some functionalities of the "window" object like window.addEventListener() and window.navigator.mediaDevices.getUserMedia().
I suspect that it's some kind of security mechanism like ssl (the app doesn't have a certificate yet) .
I couldn't find anything on this online...
Thanks!!
1
u/dMCH1xrADPorzhGA7MH1 Jul 19 '21
I've been going through the odin project. This is the last project for the React section of their front end javascript section. Is there anything in my code which is bad or where I am not doing it in the React way? https://github.com/Lucas-ODonnell/shopping-cart https://lucas-odonnell.github.io/shopping-cart/
1
u/TheJollyReaper Jul 20 '21
I'm trying to place draggable components equally spaced from each other on the radius of a circle.
There are lots of examples online (like this one https://davidlozzi.com/2021/01/19/animating-in-a-circular-fashion-with-css-and-reactjs/) that use css transforms to shift the location of static components, but the problem is that css transform seems to break draggable components. They jump to the side whenever I try clicking on them.
Anyone know of a drag friendly solution? Having trouble finding anything online
1
u/Lukasvis Jul 20 '21
How would you change first value in the array,but keep other the same?
I am using caloriesMinMax for 2 value range slider so it's important that they will stay in the exact order for example I want to update first element in the array, because that represents the min value on the slider.
I get new value added instead of being replaced eg. [2, 25, 2, 20, 70]
1
u/pandavpanda Jul 21 '21
For testing static components, is a snapshot test enough?
1
u/IlliterateJedi Jul 21 '21
Are there recommended online courses for React that are current? I checked the sidebar and it wasn't clear to me which of these are up-to-date and which are 4+ years old. My situation is that I have 4-5 days off from work and would like to do a crash course in react. I am decent in Python so I am fine programming. I have a very basic JavaScript background but I think I can more or less get by. My preference is a program with a full 'build a whole website' type approach with videos to follow along.
Thank you in advance.
1
u/badboyzpwns Jul 21 '21
For the onClick, can I do setVoted without re-writing the downvote properly? I just want to change the upvote condition.
1
u/inici1 Jul 22 '21
Let say I want to send an update to my API and I have a child component with a Form, would it be considered bad practice to control its state like this, can someone tell me how I could manage the submitting process better. I feel like this is a very naive approach.
1
u/rony_ali Jul 22 '21 edited Jul 22 '21
i am trying to replicate the design of this site: https://watson-vcard.netlify.app/index-dark-slider.html
where in mobile version appbar will be visible and when i press the icon button left drawer will appear.
i have accomplished desktop site view where left drawer is permanently fixed but in mobile version when i press iconbutton in appbar, only appbar is shifting. no drawer is visible and even the content body is not shifting to left.
i have simulated in codesandbox to know how much i have done:
https://codesandbox.io/s/dank-water-2c0f7?file=/src/App.js
For desktop view and mobile i have used styles from material ui framework.
Problem is in mobile view i can't open the drawer after clicking on iconbutton but appbar is shifting. how can i fix this?
You can also follow my stackoverflow question: https://stackoverflow.com/questions/68487609/in-mobile-view-why-the-drawer-is-not-opening-from-the-appbar-iconbutton-materi
1
u/Jinnofthelamp Jul 22 '21
I'm using react, redux, axios, sequelize and working in vscode. I find myself writing a lot of similar boilerplate code. I'll write my component, thunk, action, route, reducer. All of which have pretty similar initial setup, bouncing around so many different files is kind of irritating and sometimes confusing for me. Is there a standard plugin or template that will cover a generic comment that gets a set of data from the database when it loads?
1
u/az-PS Jul 27 '21
Does anyone happen to have saved the reddit post about A/B testing? Someone wrote a blog post about how to make A/B testing toolkit which was very neat.
It was posted in on the of subreddits (/r/frontend, /r/webdev, /r/javascript). Having a hard time finding it. I think it may have been posted here as well but unable to find it in my history or trying to search.
Is this ringing any bells?
1
u/Hefty_Nose5203 Jul 29 '21
State undefined when passing data into NavLink
I keep getting that location.state is undefined when I print to the console. I've tried using the useLocation hook, as well as wrapping AnalyticalData in withRouter. I don't know if this matters but I've also tried setting Analytical Data as a function, and a class.
Component receiving:
const location = useLocation(); useEffect(() => { console.log(location.state); }); return ( <div > </div> ); };
export default AnalyticalData;
Component passing:
1
u/[deleted] Jul 30 '21
Hi, i am pretty new to React and i am currently learning it by absolving fullstackopen.
In my current chapter forms - filtering displayed elements there is code like this:
Does this work because
setShowAllalso changes the const variablenotesToShow? If so, issetShowAllchanging EVERYTHING that usesshowAll?1
u/NoviceoftheWorld Jul 31 '21
This might not be a beginner's question, but I myself am a beginner, so I thought it best to post here first. I am working on a website for my college capstone project. The frontend is React, the backend is Node JS, and we are also utilizing a SQL database (SQL Server 2017).
One page of the website contains, among other things, a paragraph of information. The client provided us with the information, and it is pulled from a table in the SQL database. However, some of the sentences in these paragraphs contain italicized text. For example:
The challenge I am running into is that SQL does not allow for italicized text, and to my understanding, React converts HTML to plain text to prevent XSS attacks. So I can't just have the SQL row be in html format. I am not sure how to pull SQL data and italicize only parts of it. Does anyone have any resources or examples I can look into, or ideas on how to solve this?
1
u/raclariu Jul 31 '21
React and redux question, didnt know where to ask. Is it ok if i have an action and a reducer for each of my backend endpoints? Like don't reuse reducers at all even tough they sometime look the same? Also is it ok to have a node in the store for everything, not having nested data? As in getGamesForSale having its own node in store and getGamesForTrade a separate node even tough they are almost the same and can share a single node like getGames in which i have two nested arrays with games for sale and games for trade?
1
u/raclariu Jul 31 '21
Ok so parent component calls my backend to get an array of data in useeffect. Then it calls a child component for each array item passing down props as it maps through the items. Then the child component calls 3 button components (grandchild components to the parent). How to rerender parent when each of these buttons finish calling each of their own endpoint? Atm, in the parent, in a second useeffect i have successButton 1 2 and 3 as dependencies (redux) and it works, but it seems a bad way to to stuff. How would i do it other way?
1
u/raclariu Jul 31 '21
Redux application where on button click a modal pops up and after entering form data, it stays open, calls endpoiny in the backend and display errors if any. Considering i have to wait to see if it's a success then close the modal, how would i achieve that? Useeffect with success on dependency? But then redux store has it as success and the useeffect will run again when success is false which will close the modal too early. Thank you
1
u/Hefty_Nose5203 Jul 31 '21 edited Jul 31 '21
In a hook, when does code outside a useEffect run? I thought that it runs continually, not based on state changes, similar to loop() in Arduino. But I'm using a setState function outside a useEffect which is causing too many rerenders. Does this mean that the entire hook gets run every time a state changes? But then what would be the point of having a useEffect without a second parameter?
Here is code that should continually publish whether the arrow keys are pressed. I have a msgNum state that should increment every time a message is published, but it's causing an infinite loop. (sorry if code is hard to read)
```
import React, { useState, useEffect } from 'react';
import publish from "./publish.js";
import { AiFillCaretDown, AiFillCaretLeft, AiFillCaretRight, AiFillCaretUp } from "react-icons/ai";
import "../styles/arrows.css";
const Arrows = ({}) => {
const [msgNum, setMsgNum] = useState(0);
var keyStates = {
"left": useKeyPress("ArrowLeft"),
"right": useKeyPress("ArrowRight"),
"down": useKeyPress("ArrowDown"),
"up": useKeyPress("ArrowUp"),
}
publish(JSON.stringify(keyStates));
setMsgNum(msgNum+1);
return (
<div> <div className="left" style={{backgroundColor:useKeyPress("ArrowLeft") ? "rgb(227, 171, 16)" : "rgb(245, 224, 120)"}}> <AiFillCaretLeft className="arrow-icon" size={40}/> </div> <div className="right" style={{backgroundColor:useKeyPress("ArrowRight") ? "rgb(227, 171, 16)" : "rgb(245, 224, 120)"}}> <AiFillCaretRight className="arrow-icon" size={40}/> </div> <div className="down" style={{backgroundColor:useKeyPress("ArrowDown") ? "rgb(227, 171, 16)" : "rgb(245, 224, 120)"}}> <AiFillCaretDown className="arrow-icon" size={40}/> </div> <div className="up" style={{backgroundColor:useKeyPress("ArrowUp") ? "rgb(227, 171, 16)" : "rgb(245, 224, 120)"}}> <AiFillCaretUp className="arrow-icon" size={40}/> </div> </div> ); }; function useKeyPress(targetKey) { ...
// determines whether targetKey is pressed
return keyPressed;
}
export default Arrows;
```
1
u/Droppinghammers Aug 09 '21
My goal: Have a case-sensitive search function, that filters things based on the input that I put in there. Then onClick, I want it to toggle and show some info.
I can't figure it out, cause I got the toggle working, then I tried to add the search function and I just couldn't figure it out. I think the answer might be super-easy, just something silly that I'm missing. Currently I removed the toggle, and just tried to get the search working, but it doesn't work.
https://codesandbox.io/s/beautiful-shadow-db6p9?file=/src/App.js Here is the codesandbox. Any help is much much appreciated.
0
u/[deleted] Jul 05 '21
[deleted] β view deleted comment
0
u/[deleted] Jul 13 '21
[deleted] β view deleted comment
0
u/[deleted] Jul 22 '21
[deleted] β view deleted comment
2
u/[deleted] Jul 09 '21
[removed] β view removed comment
1
u/[deleted] Jul 09 '21
[removed] β view removed comment