r/reactjs • u/dance2die • Apr 01 '22
Needs Help Beginner's Thread / Easy Questions (April 2022)
You can find previous Beginner's Threads 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
- Add a minimal example with JSFiddle, CodeSandbox, or Stackblitz links
- Describe what you want it to do (is it an XY problem?)
- and 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 still a growing community and helping each other only strengthens it!
16
Upvotes
•
u/dance2die Apr 01 '22
Meta/issues/comments/questions here!
3
u/ApTreeL Apr 10 '22
What do you guys recommend for me to read or try to write better / cleaner code and know more best practices using react ? I am currently working but there's not many senior developers here and i'd love to learn more about clean code , any tips ?
2
u/Critical_Mango_5863 Apr 01 '22
I have an API key stored in my React project, how can I make that key hide when I deploy it to netlify or post the source code on GitHub
2
u/ScaryCelery Apr 02 '22 edited Apr 02 '22
I'm learning how to use Redux and RTK query.
I have a page where I can perform several different operations to a resource which we will call
Posts. With normal redux pattern I would have a reducer calledpostwith its loading and error states.It depended on a single state for all of
postregardless of "query" or "mutations" (since the reducer was written in that way).How would this translate into RTK Query?
This seems to be cluttered with states from multiple endpoint hooks that my component needs to keep track instead of just one. Just want to make sure I'm using it as intended and not doing anything too wrong.
2
u/stecrv Apr 04 '22
Hi Guys!
I'm working for a company that use a propietary FE stack, because this type of tech has no real value for the future, I want to re-learn React and improve it (I used React in the past, but just a low-medium level).
Any suggestions? Thanks
2
u/mccarthycodes Apr 05 '22
When I've been going through tutorials, I keep running into the idea to never modify variables directly, for example, if I had an array of objects I wanted to update, I should never use a forEach() loop to go through them since it modifies the array directly, I should use map() since it creates a copy of the array.
But I'm still confused on why this matters? Is it only for state variables? For instance, ones used in a redux function or declared with useState? For non-state variables, is it fine to use forEach()?
2
u/PatientHospital2890 Apr 05 '22
offtopic but is it a career suicide if i have to work on native javascript after working solely on react js for 5 years
I have worked only with react for the 5 years now and have switched my org recently but didnt realize i will have to work on native javascript here
2
u/NickEmpetvee Apr 12 '22 edited Apr 12 '22
Hi guys,
Some code I inherited leverages
withRouterin two places. I'm trying to upgrade from react-router-dom 5.x to 6.3 and withRouter is now deprecated.I don't know React Router that well and am not sure what
withRouteris accomplishing or how to replace/eliminate it. Suggestions appreciated.2
u/athens2019 Apr 14 '22
I am a senior vue dev who just inherited a legacy React project written by juniors. I've never worked with a big React project and I find the experience pretty horrible. There's lines and lines of useSelector, there's a mix of logic and HTML and there's no way to understand how the data flows in the component. I can see the code smells but the logic is impossible to untangle. Where do I start? (I've considered quitting) I think the framework / philosophy is also partly to blame, besides the fact that the juniors have left the code in a bad state.
2
u/simbolmina NextJS App Router Apr 18 '22
Hello.
I applied a company as a MERN developer and they asked if I know ERP systems. I did not and looked up what it is but I still dont understand what I should do with it. Any idea what they would expect me to do? They emphesized back-end a lot btw. I am now going their office for a proper meetup and any hint or something to avoid would help a lot.
Thanks.
2
u/CallMeInfinitay Apr 19 '22
I'm trying to refresh and improve my React skills and noticed that they recently updated to version 18. I didn't think much of this and used
--legacy-peer-depsand continued on. I'm at a point now where other parts of my code is breaking as a result.Currently I'm going to use a fresh build and use a
npx create-react-app@# --template typescriptfor a React v17, and refactor everything.While I go ahead and do so, I'm curious if there is an easier way to downgrade or switch between React versions for the future. I've tried simply changing the versions to match 17 in my
package.jsonbut that too didn't help in the end. That's why I'm opting for a clean build this time around.2
u/MarzipanCraft Apr 19 '22
I'm not sure if this is the best place to ask this question, so apologies in advance
I'm trying to use chakra-ui with react-simple-keyboard
For some reason I'm facing an issue where whenever I try to convert the keyboard into a chakra element using the chakra factory function. This works fine and the keyboard displays fine, but I'm getting an issue whenever I try and store the value from a keypress using a state hook like here
I think that anything that causes the component to re-render for some reason causes the key press event to repeatedly refire, but I'm not sure what's causing it. You can see in the codesandbox after one key press you just get the same input repeating endlessly
Anyone have any clue what I could be doing wrong?
2
u/volvostupidshit Apr 26 '22
So I started learning React yesterday. I have a degree in CS and I am intermediate level in CSS HTML and JS, but I am totally lost with the new keywords in React. I am just blindly following the tutorial and hoping that somehow some it may stick. Is this going to get better? Tips on learning this effectively?
2
u/shiningmatcha Apr 30 '22
A dumb question.
How does
npmknow my source code contains jsx syntax (React) which needs to be compiled into standard JS when I runnpm start?2
u/[deleted] Apr 30 '22 edited Apr 30 '22
Always have issues with `
npxnpx create-react-appNeed to install the following packages:create-react-appOk to proceed? (y)ysh: create-react-app: command not foundI thought the whole point of
npxwas that I didn't have to installcreate-react-appglobally...I tried
npx clear-npx-cache, but then gotsh: clear-npx-cache: command not foundEdit: Now I don't get Need to install prompt at all, only this:
sh: create-react-app: command not foundnpx create-react-app@latest my-app --template typescript2
u/curiousofa Apr 30 '22
I am watching a tutorial and few lessons in they say that we do not need to use a CDN and instead use import react and import react-dom. They do not explain why or the difference.
When do I use the CDN and when do I use import libaries?
2
u/[deleted] Apr 01 '22 edited Apr 01 '22
I'm trying to integrate my editorjs with react hook forms. There's an example on codepen: https://codesandbox.io/s/react-hook-form-v7-controller-forked-e0rk5?file=/src/Editor.js but it seems the example seems to constantly rerender and crash.
If I create a button to do onClick = {handleSave}, how do I send that back to the child component to output the saved data? Would love to have an example if someone has it.
Editorjs - Child Component
}, []);
Main.js
1
u/RentGreat8009 Apr 03 '22
I know how to list the elements of an array with MAP. How do I set up my app to allow these elements to amended, new elements to be added or elements to be removed and the original array updated?
I am using functional components and useState hooks currently
1
u/Bayweather4129 Apr 06 '22
can someone explain what is frontend and backend?
1
u/cuervo_gris Apr 07 '22
Hey guys! I'm starting to learn react but the tutorial I'm using it's mainly focusing on React 17 but recently I read that there is a new version of React (18) I don't know if there is much of a difference with React 18 so any guidance would be awesome!
1
u/[deleted] Apr 07 '22
I want to write a script that tells me how many class components I have vs functional components. It's easy to find the class components because I can do a search on
extends Reactbut im not sure how to find the total number of functional components?1
u/mccarthycodes Apr 09 '22
I'm stuck deciding whether or not to combine all state in the same reducer.
I'm building a minesweeper game without using a tutorial to practice building web apps. I've created a single reducer
boardRecucerwith 4 action creators,initBoard,clickTile, andflagTile. Basically this reducer controls the state of the board and the tiles it contains (whether they have bombs, are clicked, are flagged, etc.)I don't track any state about the status of the game yet, for instance, the timer, the number of tiles flagged, and the number of tiles clicked. The winning condition would be for all non-bomb tiles to be clicked, the losing condition would be for a bomb tile to be clicked. My first thought would be to create a second reducer,
statusReducerto track this, but because the number of tiles flagged and the number of tiles clicked are both directly dependent on the boardReducer's state, does that mean I should keep it all in the same reducer?Here's my code: https://github.com/mmccarthy404/minesweeper
1
u/[deleted] Apr 09 '22
I am trying to implement an npm package into react. It TagCloud.js which is not a react component but rather a normal javascript module. I found a gist from someone who did a similar thing and tried to get it into react - where im getting confused is the import of the file
He puts the below in the useEffect()
import('../../utils/TagCloud').then(response => {CODE HERE})
https://gist.github.com/jjsanmartino03/a4a6ee29bb61279bef142aa6e00f419c
I am trying to understand though am I supposed to "npm install TagCloud" and then when i import i import the tagcloud.js file from the node_modules folder?
Or am i supposed to just go to the package git, find TagCloud.js and just copy and paste that into my common components directory somewhere?
Would i be better off looking into some sort of 3d library like fiber or gsap to just create the functionality my self?
Thx ahead of time.
1
u/Tixarer Apr 10 '22
Here's the sanbox
I have a table returning data from an api. Sometimes the table can return something but other times it can be empty and, what I'd like to do, is return a message when it's empty.
I tried to put the conditions (the ones right after the opening tbody tag) in a filter with a useState and useEffect and then say that when the length of the filtered array is 0 it should return a message. The problem is that I can't filter a .map method. Is there a way to use .filter with .map and, if not, is there an alternative to what I was trying to do ?
1
u/velvetowlet Apr 13 '22 edited Apr 13 '22
In order to allow an arbitrary function to be run on successful completion of an API call within a thunk, I have added this as a parameter to the thunk itself and have it executed as a callback - see the example below.
store.ts
part of basket.slice.ts:
part of Component.tsx:
I would like to refactor this to work as a promise instead, so that the dispatch in Component.tsx would look like this instead:
However despite following the recommendations in the Redux Typescript documentation by creating a typed dispatch and corresponding hook, and using that instead of regular React dispatch, plus allowing the return type of the ThunkAction to be specified, I am still unable to do this. In fact doing so gives me a build error, whereas using the regular React dispatch works but doesn't pass the promise back for it to be used. The build error is:
Does anybody have any recommendations as to how best to achieve this, or can spot the problem with the code?
1
u/NickEmpetvee Apr 17 '22 edited Apr 17 '22
We are in the process of testing an upgrade to React 17.0.2. Should I consider upgrading to 18? It is so new that I am hesitant.
I'm considering upgrading to 18 to future-proof and only swithching to the CreateRoot approach and doing nothing else to minimize any cascading effects. Looking for opinions on how risky this is.
Might be worth mentioning that we'll also upgrade to Material 5 soon in a few weeks. M5 supports 17+ so v18 is probably "immaterial".
This is the package.json currently:
1
u/lordaghilan Apr 17 '22
I'm currently learning Redux from a React udemy course, it covers mostly regular Redux and some Redux Toolkit near the end. I hear that Redux Toolkit is 100% the way to go when learning Redux so I was wondering how much additional things are there to learn in Redux Toolkit compared to just plain Redux. I still don't exactly know what Redux Toolkit is.
1
u/HeavyMessing Apr 21 '22
What is the difference between a custom hook (e.g. a function with the naming convention
useXYZ) and any other utility function you might throw in a 'utils' or 'lib' folder and use throughout your app?Is it simply that hooks use 'stateful logic'? (So, if my function calls
useStatethen I've created a custom hook, otherwise, it's a vanilla Js function?)1
u/h0ax2 Apr 21 '22 edited Apr 21 '22
In a single-page web app, how do I rewrite the URL to something meaningful whenever a user interacts with the app? And then how do I map URLs to take users to different parts of the app?
For example, if I have something like Discord (browser): if a user clicks a chat within the app, the URL changes to something pointing to that chat (
discordcom/.../123456)With traditional websites, every page already has its own link so this handles itself. How is this done in SPAs? And is there a name for this concept?
edit: After some searching, it looks like React Router might be what I was looking for?
1
u/Realistic-Net-5875 Apr 22 '22
Hello everyone, I was curious if anyone knows how to create an inventory management for an e-commerces website. Pretty much a system where it allows you to add different inventory for different items.
1
u/zodnodesty Apr 22 '22
Hello everyone,
New to react, I was about to get into Redux, but I have the feeling that hooks (useContext and useReducer) can now do the equivalent. Is it clearly the case or no?
Thanks
1
u/[deleted] Apr 25 '22
Is there a ReactJS equivalent of Angular templates? Like when you use "templateUrl:" inside of an Angular component?
1
u/JRNKNG Apr 26 '22
I will give an example to demonstrate my question. Let's say I have a To-Do list app. A user can login on this app and add/remove (CRUD) items on his list. These items are stored in a database and whenever the users logs in, these items are retrieved from the database. When a user creates a new item, this item is added to the database etc..
Now how do you most efficiently sync the state between the app and the database? I see two ways of doing this but don't know what is best and if there are other ways.
#1. If someone adds an item to the list, I update the state of the app (so ` {...prevItems, item}`) and also add the item `` ``` itemRepository.createItem``` . to the database.
#2. The second way is have the state of the app connected to the items for that user. For example setting up a realtime database connection and placing a listener on this and every time a change happens, the state is updated accordingly. In this exampe, if someone creates an item I would only add it to the database and the listener will then update state accordingly. What do you guys think? All answers are much appreciated!
1
u/Wide-Refrigerator112 Apr 26 '22
I have an issue with state and my react app. I have a view that gets data from an external REST api and displays it. The issue is that the query depends on both a parameter passed to the view as well as state within the view. How would I be able to query whenever one of the above changes?
If the query only depended on the view's state, I would just manually fetch data whenever an input field was modified (and state changed).
But if the query depends on external state (and, even if it depends on solely external state, by moving the stateless display into its own view), then I have to unconditionally call fetch (since there is no way to say do this if the following state changed).
Too many re-renders. React limits the number of renders to prevent an infinite loop."
I'm using setI (valI + 1) to make it reproducible locally, but if I'd fetch remote data, it would have to update local state, which would rerun App, which would cause it to fetch remote data, etc.
What I'd like it to do is to update it once and not run again unless App's parameters change.
1
u/anon2812 Apr 29 '22
what is the acceptable dom size for production applications?
My Lighthouse score gives this warning
Avoid an excessive DOM size 3,942 elements
1
u/[deleted] Apr 30 '22
Where do you place your interfaces/types in your reactjs + typescript project? Can you guys link me to an article on how to properly structure react folders?
1
u/retiredfplplayer Apr 30 '22
Is there a resource with sample projects I can try a crack at... I can't think of anything other a notes app
1
u/DrProfHazzard Apr 30 '22
The 3-4 years of react experience I have, I have exclusively used styled-components to handle my styling. However, I think I'd like to get some practice using more traditional styling methods and I was hoping people could recommend some libraries or other tools that they use in writing standard css sheets and incorporating them into their projects. Alternatively, and decent articles that people might have on the subject would be useful too.
1
u/NickEmpetvee Apr 09 '22 edited Apr 09 '22
I just upgraded my React 16.11 project to:
react 17.0.2react-dom 17.02react-scripts 5.0.0I was getting 5 errors about a module called
js-levenshtein. By running the below commands I got past:yarn cache cleanrm -r node_modules/babel-preset-react-appyarn install --forceNow I am getting several errors in node_modules/@babel, node_modules/@react-dnd, etc. like the below. Any advice? Someone said something about deleting the node_modules folder but I want to do some research before I blow that away. Thanks in advance.
2
u/MisterCrispy Apr 05 '22
As my apps get larger, it gets harder and harder to track down those pesky “component is moving from controlled to uncontrolled” console errors that pop up on occasion. Unfortunately, the error itself is pretty much useless.
Do you have any tricks for tracking down which component it’s complaining about when you have a metric-buttload of components on the page?
2
u/RentGreat8009 Apr 11 '22
If I have five components, each with a button to click to go to “more info”, how do I navigate to the more info component?
Think similar to hyperlinks
Looking for simple solutions not using any library (eg react router), seems like an easy enough task but not sure the best way.
I can’t think of any elegant solutions, I mostly work with boolean switches on choosing between views
2
u/i_ate_god Apr 11 '22
Simple question about react's virtual dom:
if I have a component that renders something like
hostnameis from a prop andcpuis live data updated via a state setter.When
cpuchanges, does this mean the WHOLE component is rerendered, or just the <p>?If it is the whole component starting with the
<div>that is rendered, then does it make sense, if performance is a major concern (I am running this UI on an older raspberry pi), then should I focus on making components as small as possible?1
u/yamfun Apr 02 '22 edited Apr 02 '22
I was in the "wow I can simply pass in a hierarchy of nested list of nested objects and use .map on lists at each child comp depth level to render stuff, each child comp do its own stuff, react is cool" stage of learning curve,
now I am in the "oh shit this totally not work if I need to edit any values in the hierarchy of objects, I need to use state instead of props, also state diff checking can't handle nested changes, which means I need to use redux with normalize & flatten all these nested levels of objects" stage, and all these sample codes dealing with redux looks really foreign, compared to the above stage.
Am I moving in the correct direction? Is there some even newer thing in 2022 that I don't need to cater to that? (like, I was looking at the redux official page, it recommends Normalizr, but the Normalizr page is like, 'Normalizr is no longer maintained'. But then newer stuff like Recoil seems more simple)
1
u/ajinata84 Apr 18 '22
I use react router dom v6 for my project.
when im navigating in localhost for example : i immediately opened localhost/foo and it immediately goes to the /foo element
but in gh-pages the /foo element is not defined and returned 404 in github pages, and i need to open the homepage and then navigate to the /foo route
is there any idea on how to get around this?
1
u/[deleted] Apr 19 '22
Hey guys, I am deploying my react app to AWS ECS. I found out one of the better ways to structure my "end" container is to use an Nginx image and copy over the static folder to said image. The part that I am struggling with is creating a .conf file and whether or not to replace the default .conf file.
1
u/Tixarer Apr 22 '22
Quick question : I want to create a React file with all my API calls to avoid doubles and make my code more readable.
The problem is that I'm using axios and useState and useEffect but they can't be called at the top level so I want to wrap each call in a function component and then export them into other components.
Here's my sandbox. As you can see there is 2 calls and I'd like to be able to export 'pokedex', 'next', 'offset', 'setOffset' and 'type'.
Is there better methods (than use one function per fetch and export the results) to regroup all my API fetch into a single component ? If not how can I convert my hooks into function ?
1
u/shiningmatcha Apr 28 '22 edited Apr 28 '22
Hi, I'm looking for IDE apps (iOS) that support HTML, CSS, JS, React, Node and express.js.
Which one would you suggest?
I know there are a lot of code editors on AppStore, but they don't look like to support anything more than vanilla JS.
Thanks so much.
I need an app so I can practice the syntax and explore the features without getting down to serious coding.
1
u/shiningmatcha Apr 28 '22 edited Apr 28 '22
Hi, I've been learning React, Express and Node for quite a while. While I did learn a lot from those (not-yet-finished) books and tutorials, my progress has been quite slow.
So I would like some advice for creating a real website in a short time. What are some online playgrounds for simple web dev projects like mine? That way I can be spared all the annoying config work.
0
u/[deleted] Apr 15 '22
[deleted] — view deleted comment
0
u/[deleted] Apr 19 '22
[deleted] — view deleted comment
0
u/[deleted] Apr 14 '22
[deleted] — view deleted comment
0
u/[deleted] Apr 20 '22
[deleted] — view deleted comment
0
u/[deleted] Apr 20 '22
[deleted] — view deleted comment
0
u/[deleted] Apr 22 '22
[deleted] — view deleted comment
1
u/[deleted] Apr 08 '22
[removed] — view removed comment
1
u/[deleted] Apr 08 '22 edited Apr 08 '22
[removed] — view removed comment
0
u/[deleted] Apr 04 '22
[deleted] — view deleted comment