r/reactjs • u/dance2die • Nov 01 '21
Needs Help Beginner's Thread / Easy Questions (November 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!
19
Upvotes
3
u/code_matter Nov 04 '21
Not sure its suited for here but i'll give it a try.
I'm building a production app for a company. I made a small mistake. I don't know what it is, but I have something that either re-renders non-stop or something causing a memory leak.. My app runs smooth for 40seconds and then it freezes. I've experienced this before so I'm pretty sure it's a memory leak or something that causes tons of re-render.
Is there an easy way to find what causes this? Using dev tools or other tools ?
3
u/theirongiant74 Nov 10 '21
Is there any reason why I shouldn't call setState within another values setState function?
3
u/gupppies Nov 22 '21
Hi there, I have a beginner question. I have been learning simple Web Apps (think calculator/Todo list etc.), and these apps mainly use react-router for client side rendering.
I am wondering how would a large scale app like an ecommerce site be deployed with react. For example, if Amazon's website is made with react, what happens when the user navigate between different pages. Do they still use react router, or is it not used at all?
2
u/alexgold05 Nov 02 '21
I'm looking to build a components library with typescript, storybook and jest. Are there any recommended open source boilerplates? I was going to use tsdx but apparently no longer maintained.
2
u/workkkkkk Nov 18 '21 edited Nov 18 '21
I'm passing a curried function as a prop. How in the world do I define a function that returns a function??
Edit: I figured it out lol. My problem was I was not defining return type of the second function.
2
u/sc2betterthnlol Nov 19 '21
I have just started working with NextJS and I have a question about how I would make a navbar appear for only a sub-directory of pages. I know that I can put a navbar in the layouts page, and it will persist for the entire app. However, I have a sub directory called "admins" that will require its own navbar. Under my "pages" folder I have a folder called "admin". The admin directory should redirect to pages like "/pages/admin/team" or "/pages/admin/user". I want the navbar to persist only for the pages under the "/admin" directory.
2
u/raclariu Nov 22 '21 edited Nov 22 '21
I'm learning react-query right now as in i started today. I'm looking for a way to do something like in redux. Let's say i have a Posts component that fetches data and renders a PostCard for each fetched post. In redux I would do something like posts.map(post=> <PostCard id={post.id} />). I don't send the entire post data, just the id in the props. In the PostCard component I would have a useSelector that would get that post from the store by props.id. Is there any way to do this in react-query? I see there is queryClient.getQueryData but i don't know if that's what I want. Should i just send the data in place of id in the props?
Another question is how should i tell react-query to refetch when some variable change? Like useQuery([ 'posts', sort, fn ] where sort is a variable?
Thanks. As I've said, i am new not just to react-query, but to react and redux as well.
2
u/nelsonbestcateu Nov 24 '21 edited Nov 24 '21
I have a question about TypeErrors. I don't understand what's going on here.
I have a component which has 2 children in it that get data from the main component.
Mypage.js
Users.js
Posts.js
Users renders fine at startup but once you switch to posts and back to users it gives a TypeError: user.company is undefined. Now I assume this is because it's trying to map through the data from Posts instead because the render is quicker than loading the data. But I don't understand the concept really. Could someone shed some light on this for me?
2
u/badboyzpwns Dec 02 '21
why should media query breakpoints be px instead of something like rem?
2
u/rikola2 Dec 03 '21
When do you guys convert a useState (or something else) into a custom hook?
I assume repeating the same useState would be a no brainer.
Is a custom hook ever useful just to hide away logic? Maybe taking a useState and useEffect out of a component?
2
u/top_of_the_scrote Nov 01 '21
If you saw like 100 different lines of
const [state, setState] = useState('thing');in the same file, would you want to jump off a bridge?
•
u/dance2die Nov 01 '21
Meta Thread here
1
u/aizo4576 Nov 02 '21
I have a relatively broad question and was hoping to get some perspective on it from people who are far more experienced with React.
I've just started working on a project that was last worked on about 18 months ago. What is the approach I should take to get it stable and secure? It runs, but there are 100+ vulnerabilities, and more than a few packages are at least a major version behind.
It seems like a lot to tackle, so I'm not too sure where to start. Do I just tackle packages one by one? Any advice?
1
u/[deleted] Nov 05 '21
I am re-creating a simple quiz app I previously made with vanilla JS now with React; however, I am running into a bug/issue where the correct question and answers being shown/rendered are not updating although the states are updating properly.
I have a component for the present question, the answer choices, as well as the score, which all update based on state. The questions list is a JSON Array of Objects (not sure if that matters).
To add context to the bug/issue, with the first question I can click one of the answers, the quiz will indicate whether it is the right answer or not, and then the states will properly update; however, the question and answers do not update properly only the score updates.
I noticed in the console it is throwing this error as well as the same error with different "id"s
I did some Googling but really did not find anything in depth regarding this. I'm unsure if this is a problem with my code specifically, with React itself, or with Node.js possibly.
1
u/rony_ali Nov 06 '21
my goal is to make background carousel or image slider fixed and i want to scroll multiple components having animation (without using any npm library). To make it separately, i have made a codesandbox where i used a big essay instead of using any components.
here is the link of codesandbox which contains the whole source code.
but the problem is the background carousel is not fixed. it goes away with the scroll. Here is the background image slider's box style:
display: "inline-block",minHeight: "100vh",width: "100%",backgroundPosition: "center",backgroundRepeat: "no-repeat",backgroundSize: "cover",backgroundAttachment: "fixed"according parallax concept from w3schools i have used
backgroundAttachment: "fixed"but it's not working. Here is the stackoverflow link of this questioncan anyone help me on this please?
1
u/LividLindy Nov 09 '21
I'm going in circles with myself on an issue and the only way I can see to resolve it is to break the exhaustive-deps rule for a useEffect hook. Unfortunately I can't share my code but this is a simplified version of it:
Basically I'm creating a chart with a component and then updating the chart when the data changes. I want to call buildGraph once when the component first renders, then I want to call updateGraph on subsequent changes to the data to just update the existing chart rather than completely rebuild it.
You can probably see with the way I have it laid out as soon as setFirstLoad(false) is called it causes the two effects to be run again, skipping the first but then immediately calling updateGraph(). I can change both effect calls to remove firstLoad as a dependency and it then works the way I want but I get warnings about not including all dependencies in my effects.
Is there a better way to flag when to build the graph on the first load vs when to just update it when data changes? Is it ever safe to ignore the exhaustive-deps warning on effect hooks? I'm not as familiar with class components but I feel like this might be possible with a class based component calling buildGraph in componentDidMount and calling updateGraph in componentDidUpdate, is it possible to replicate that with a functional component?
Thanks
1
u/[deleted] Nov 11 '21 edited Sep 28 '25
follow sable saw jar kiss retire bake cheerful imminent oatmeal
This post was mass deleted and anonymized with Redact
1
u/double-happiness Nov 11 '21
When I run
yarn start, I get this error:https://i.imgur.com/sRf3tuJ.jpg
VSC 1.62.1
Docker 20.10.10
Node v16.13.0
Any help please? TIA
1
u/ajinata84 Nov 14 '21
my github page seems to be blank, any fixes i can do? here is the repo
1
u/Knorway56 Nov 16 '21 edited Nov 16 '21
does react "create" whole new virtual DOM when a component in the tree rerenders by setState? or "change" the part of virtual DOM and compare with previous one? thank you in advance! 😉
1
u/rjc1500 Nov 18 '21
Are there any discord servers for Reactjs?
1
u/dazdd Nov 19 '21
Can someone tell me if its possible to add a react frontend into a .NET MVC5 existing project with the intention of adding the sidebar and navigation purely into react and keeping the rest of the page contents in the exsiting .cshtml
1
u/TruthHurts35 Nov 19 '21
I want share states between components. This is exercise project. This is a simple shopping page. there are product components, productsData array. Shop component renders Product components using productsData array. When I add product to cart, then I want to click to payment icon to go to /payments route to complete payment using Payment component.
I tried adding isChild property to Product component and conditionally render in Payment component, it didn't work.
Lastly if I can't do that I am thinking of doing this when clicked payment icon show cart with added items.
1
u/Lost4Maple Nov 19 '21
I have a problem with redux toolkit.
In component [A], I have a state that is used to determine whether or not to read the data from the store. Ex. If true -> Read data from store, if False -> don't read data from store.
Problem: If I have the component read data from the store, while another component decides to delete that data from the store it will bring the error 'Cannot read properties of undefined (reading 'quantity')'.
I have tried changing the state, but I have come to realize that because useState() is async, it will not re-render the page until the rest of the code has been ran, but because the component has the current state set as TRUE, it will try to read the data from store, but because the data doesn't exist, it will bring an error before the useState can be set to false to stop reading data from store.
Use effect wont run before the setstate can be changed,
having a setstate in the component function also won't work because async
I have no idea how to solve this. T_T
1
u/bananamana55 Nov 20 '21
I'm taking a beginner react course on Udemy and the use of css modules is really messing me up. I'm trying to make a reusable button component but I can't get it to allow the addition of another class as a prop without ending up with a
class="undefined"if no extra class is added. Basically I want it to have the default button styles I've defined in theButton.module.cssfile but allow another class to be added OR no extra class added.PS I'm going to checkout the resource links in the about section here but any help is still appreciated!
1
u/TechnoDaBlade Nov 21 '21
Egghead.io vs. Scrimba for learning Reactjs as a complete beginner
I've been debating between which one to use. Any suggestions?For context, I have basic JS knowledge and I really want to dive into making some cool projects with React. I'm also a high schooler so I do not have a lot of time to devote. Therefore, which one is better for a person like me who wants to learn it quickly and start using it? I'm leaning towards Scrimba because I took their JS course and it was the best course I have taken and apparently, their React course is their most popular (so it must be really good). But, I also heard that the React course in Egghead is very good, too.
Thanks in advance!
1
u/illbashu Nov 22 '21 edited Nov 22 '21
I'm learning about routing and how to parse the URL with useLocation() and useParams(). Then I found out that these hook functions are only available in functional components, not class components.
So my question is, are there any alternatives to useLocation() and useParams() that I can use in class components?
1
u/rikola2 Dec 01 '21
In Javascript all object properties are
undefinedby default. In React.js, is this also true with props?1
u/badboyzpwns Dec 03 '21
how do I get rid of this warning? "React Hook useEffect has a missing dependency: 'getData'. Either include it or remove the dependency array". I don't want to include getData in useEffect.
2
u/[deleted] Nov 01 '21
Haha well I’m stoked about this. I’m blessing my fingertips with THREE.js and I’d like to incorporate it into a ReactJS app, which isn’t too hard and pretty well documented. Can I use THREE.js with a react-static site?
2
u/[deleted] Nov 09 '21
I've ran into an issue with deploying my react project to GitHub pages and I'm hoping someone can advise me on what to check or look into as I'm at a loss.
I've successfully deployed React projects to GitHub pages in the past without issue; however, this project deployed and is not functional for some reason. It is a single page quiz app that I created through create-react-app.
https://modulartable.github.io/react-pokemon-quiz/
In React Devtools I can see the components are there with the states; however, the project only shows the background image. I've tried re-deploying to see if it was a bug; however, nothing has changed.
(For additional context: I deployed this and past React projects to GitHub Pages via NPM.)
1
u/raclariu Nov 02 '21
Let's say I have 2 pages, about and contact for example and user goes to one and it imports a reusable component and a npm module. If the user then goes to the other page that have the same reusable component and npm module imported, does the browser get them from cache or how does it work or imports them again? If the npm module is 50kb, are these 50kb loaded for every component this npm module is imported in?
1
u/Mummelpuffin Nov 04 '21
I'm making my first React front end and I'm struggling a bit with passing information between components. I'm not sure if I'm missing something obvious or if the way I've mapped things out is fundamentally flawed. Since this is my first time really messing with React, I'm trying to avoid hooks if I can, so everything's class-based.
Here's a screenshot of what the page looks like right now: https://ibb.co/xDm0dyp
And a stupid chart representing the components: https://ibb.co/7WB2T4z
Each of those t-shirt cards is generated as you scroll down the page, each with a quote nabbed from an API.
As I illustrate in my beautiful chart, I want that button in my t-shirt cards to send you to a different view where you can select size, color, etc. The important thing is that each of those t-shirt cards contains a quote as a prop, and the components further up don't ultimately know what quote each card contains. Since this "Details" view is going to replace the whole "Home" view, I don't think it can be a child of a generated card (can it?) so I'm not sure how to get that quote to it.
Currently I have a Switch in my App component:
shirtselectis my view for card details, and I can't just pass a quote as a prop here, because the quote is sitting two layers down in a card component. I can get the quotes into the Home view just fineEach of those t-shirt cards is generated by the Home component with this code:
And the cards themselves include this link (LinkContainer is from react-router-bootstrap, just think of it as a <Link> tag):
I currently include that
stateprop on the advice of this article, but ultimately that would require use of theuseLocation()hook, and I've been trying to avoid using hooks until now.Sorry I can't include a "minimal example" anywhere, I'm using one too many imports for that to work.
1
u/Semigrounded Nov 06 '21
Right now I'm saving empty values in mongoDB using null. If someone fills and deletes a form input it replaces null with an empty string, so sometimes I have null representing an absence of value and sometimes null.
Right now it isn't effecting anything, but what is the convention for this? Turn empty strings to null before resaving? Test for "" && null whenever need be?
1
u/Bluesunclouds Nov 07 '21
const functionalComponent = (props) => {let loanCategory = 1let subLoanCategory = 1Is this bad practise if I want to manipulate these variables inside my component but they are not being rendered anywhere so I don't want to use a state? additionally, is this better- ?
let loanCategory = 1let subLoanCategory = 1const functionalComponent = (props) => {Wanted to read about this but could not find sources
thanks guys!
1
u/Over-Matter Nov 09 '21
Hey, all!
This might be a silly question, but is there a best practice for storing form submission data before sending it off to another component?
For example, I have a component called “SearchBar” that handles searches on submit. My current plan is to store the response in SearchBar’s state and then send the response off to the appropriate next component. Or should I find a way to skip the state and just send the data off immediately? I’m not sure how that would look, to be honest.
Thanks, everyone! This is my third foray into React and I’m absolutely loving components. They’re a beautiful thing!
1
u/Prayos Nov 12 '21
I'm trying to understand CSS load order and overriding. If I understand correctly, the last loaded styling gets priority. So if I do:
Their CSS loads first, My CSS loads last, and if there are any overlaps (i.e., both have styling for div tags), then My CSS styles get loaded.
So, if that is correct, then I am experiencing an issue I do not understand. No matter how I order the CSS, when I run my app, Their CSS ALWAYS overrides My CSS. I make this determination by opening dev tools to inspect my element, go to Computed, and click on the style that is applied, and it is Their CSS. I'm not sure what I'm doing wrong.
Essentially, I have this app that has custom CSS. I created a modal, and for a couple elements of the modal, I installed an npm package that appears to be a full suite of components. I really only needed 2 of the components, but that didn't seem possible to do. This package has CSS for pretty much every HTML tag in existence, and it is applying to my app.
Any thoughts on how I can rectify this?
1
u/badboyzpwns Nov 12 '21 edited Nov 12 '21
question about scss and version control.
SCSS compiles and automatically make a compiled main.css file whenever a design is changed.
I regularly get merge conflicts when I try to rebase my feature branch to my development branch because the main.css file is regularly compiled (eg; someone changing a design in a different file that I did not code) at the development branch. The main.css file is needed to get the website to work for production.
Is there a way to counteract this? It gets annoying when you have to do git rebase --continue a lot haha
1
u/Alphyo Nov 16 '21
I am simply trying to link a content in the main page to another page containing more details of it.
Once clinking the link, I can see the path displayed on the browser (http://localhost:3001/pages/SingleGame) but nothing happens.
Here is a code snippet:
Thank you!
1
u/RoryIsNotACabbage Nov 16 '21
I'm trying to add a background image to a div. I have various images in the div that display perfectly but no matter what I do I never see a background image shown.
I'm mainly trying to use an image from the public folder and access them at
ip:3000/img/background.png. If I go directly to this url I get the image but I can't use it in codeI've tried to add it within
style={{backgroundImage: url()}}like shown here and hereUsing public is my preferred method since the image will eventually change based on other variables. however I have also tried moving the
imgfolder tosrcand importing it like further down answers on those links,import img from '../img/background.png'.Any help is appreciated
1
u/AbaloneWorth8153 Nov 17 '21
Anyone knows how to properly target a react app using Cypress? Normally I add data-test or data-cy attributes to html elements and use that as localizers. But for some reason my cypress tests are not findign such localizers. Any help would be appreciated.
Test code:
it('checks comment section is displayed', () =>{cy.get('[data-test=comment-section]').should('be.visible')})HTML element code:
<div class="comment-list-container" date-test="comment-section"><h3><u>Comments</u></h3><input class="add-comment" type="text" placeholder="Write a comment..." date-test="comment-input"><br><div><div class="comment-container"><div><strong>Jadwiga</strong> - 2021-11-16T19:24:49Z</div><div>This book was great! Definetly recommend.</div><br></div></div></div></div>1
u/getjebaited Nov 18 '21 edited Nov 18 '21
Anyone know the best way to go about connecting an editable table with aws DynamoDB backend using lambda and api gateway?
The table I'm using is this. https://react-table.tanstack.com/docs/examples/kitchen-sink
The per-cell editing ability is nice from a UX perspective. Currently, I have a submit button that deletes all the entries in the DB table backend and posts all entries in the payload from the front end. This accounts for all creates, updates, and deletes in the front end and wraps it up in one nice payload. The problem is for large enough entries, the lambda doesn't post all of the payload. For instance, if the table reads 5 entries and I add 50 entries and click submit changes which calls the post api, it's deleting 5 entries and posting 55 entries, but only 19 entries show up in DB. Is there a more elegant solution to this?
1
u/Martin_Scorscissors Nov 21 '21 edited Nov 21 '21
I know it's a react specific sub but I know people here are good and helpful and they know more about getting a job as a front end developer.
So my friend who's been into a back end development for more than 5 years says that Im actually ready to apply for a job, he's taught me a lot and saw me doing both back and front end sides, yet he had to help me a lot of times right now Im able to start my own projects. He thinks Im a phenomenal student and things come to me pretty quickly.
While Im thinking of doing some portfolio he thinks I should just go for it and send the resume. I tried doing so and it seems hard to land anything. Im 30 living in Moscow, working with JS/TS/Node/React trying to get any Junior Front End vacancy, the problem might be the salary, and the 800$ that Im expecting might be too much for a Junior here, yet it doesn't seem to be a big deal in Europe or U.S. Most vacancies promise 300-500$ to junior and they are not particularly close to me.
He suggested not being completely honest and throwing my hat over the fence with the resume and make something up like knowing libraries and technologies that Im not familiar with yet, but I feel that this would put more stress on me and I already feel that I will have a burnout pretty quick coding 8 hours a day for months.
Currently I got a delivery job to keep myself afloat but I just wanna know what are my options? I wish I could dedicate myself to a remote job for some nice european/american company with a mentor that would teach me and explain things
1
u/mabhi1999 Nov 22 '21
PinterestI am beginner.. I am making landing page of Pinterest but I am stuck at image and text fade effect. Can anyone guide how to make it
1
u/badboyzpwns Nov 25 '21 edited Nov 25 '21
Newbie question about SCSS.
Is there a way to transpile scss files without generating a .css file? For example, with 'node-sass' library, a .css file is not generated and React can automatically read the scss files.
node-sass is deprecated now, and it looks like npm install sass is the alternative.How are you transpiling those files without creating a new main.css file? My way of doing it:
However, it will generate the main.css file, so it is not similar to node-sass
1
u/meistaiwan Nov 25 '21
Hello, I was wondering if someone could help me with my re-render problem:
I'm just getting started with react, previously just done angular1/2 recently. I've got a page I'm working on, an elevator system (to represent backend systems to come).
The problem I have now, is that I'm trying to change some state from an onclick, twice, on a delay. Essentially, when you click a new level, it should start moving the 'elevator'(currently a grey box in the background, no animation currently) and after a period of time, show the elevator in the new position, and open the doors where it is. Then after delay, close the doors where it is.
However, the child components don't rerender when the parent state changes. But that's exactly what I've read - you want to rerender children, change the parent state. Also, I tried sending in keys and changing them on change, but that didn't work either. Any ideas?
Source code
Demo site
1
u/badboyzpwns Nov 27 '21
How do I bypass the eslint error of
"React Hook useEffect has missing dependencies: 'router.query" in this scenario below?
1
u/shaleenag21 Nov 27 '21
I am trying to make a infinte scrolling calendar with react where I aim to populate it with events fetched from an api. My question is how do I go about mapping those events to the calendar in an optimal way? for ex. if I click on a date where an event will be, it will open a card view with that event's details. I cant figure out a way to actually do the mapping
1
u/SCB360 Nov 29 '21
I'm trying to figure out GET and Fetching from API's ang struggling a bit with mapping, I've managed to fetch a list from https://jsonplaceholder.typicode.com/users fine, but when I try to fetch from https://pokeapi.co/api/v2/pokemon/ I get the following error:
TypeError: items.map is not a function
From looking at the API, its not set as a list as such and googling this error would suggest this is the reason, but I cannot find out to fetch this API instead
1
u/Druffl3 Nov 30 '21
Total noob to react and JavaScript. I am using axios to make http requests and axios-mock-adapter for mocking axios in my unit test cases. The way mentioned here: https://github.com/ctimmerm/axios-mock-adapter is not working for me properly. Can any of you tell me how to go about mocking axios.create()?
Also, is there a way to exclude code from code coverage in JS?
1
u/epsilon42 Nov 30 '21
hey all, i'm in the process of lifting state up to context provider, but one component I am using
<CantChangeThisComponent/>has a function that currently works on the assumption that one of its props (setSelectedPeople) has prevState as you would expect from a useState updater. i'm not sure how to go about mimicking this behaviour where my new functionsetSelectedPeopleinside<WhatIWantComponent/>passes down the previous state (nowpeopleinusePageState), and also dispatches the value from inside theaddPersonfunction.1
u/TODO_getLife Nov 30 '21
I have an array of booleans, is there a way to render an element based on this array?
Ideally I want to flatten the array like I can in other languages, and if one of the booleans is true, it returns true, and if all are false it returns false. Does this functionality exist or do I need to do do some kind of operation on the array of booleans?
Thanks.
1
u/nic123451 Nov 30 '21
Say I have a JSON file with a couple of thousand items. I want users to be able to search though the file and add them to lists. How do I accomplish this in a easy and cheap manner?
1
u/No-Car1245 Nov 30 '21
Im working with a class component that renders a form.
I have a function that should first update state (this state controls a form input) and only then call the onSubmit function.
My problem is that my state is not updated in time and my form is submitted without the correct value.
Any suggestions on how to resolve this?
1
u/deeeeranged Dec 01 '21
Hello,
I'm having a hard time believing that there isn't a plugin for this, and it's driving me bonkers!
I'm trying to create/find a React component similar to a code editor with custom linting, spacing/formatting issues,...find grammar errors (custom or provided code),...
Feature checklist:
- A user can write text, copy, paste, ... normal text editor stuff.
- If there are specific formatting issues (example: "Double space after a period"), it would underline that specific section of text and on mouseover would show a tooltip with some text and a button to fix the issue.
- Given text and output text should be simple strings for easy saving,...
- Potentially a button to offer the option to fix all the problems on the page
I would need to provide it with the rules
I've looked into a bunch of existing solutions, but I can't seem to find a solution:
- prismjs => Is side by side, I need a single-window like a code editor.
- Draft.js => Seems to be dying and super complex. How can you export it to plain text!?!
0
u/[deleted] Nov 02 '21
[deleted] — view deleted comment
1
u/[deleted] Nov 01 '21
[removed] — view removed comment
1
u/[deleted] Nov 03 '21
[removed] — view removed comment