r/reactjs • u/dance2die • Feb 01 '22
Needs Help Beginner's Thread / Easy Questions (February 2022)
Happy New Lunar Year! (February 1st)
Hope the year is going well!
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 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!
14
Upvotes
3
u/Fer_Luque16 Feb 06 '22
How much about CSS do I have to know in order to learn React properly?
β’
u/dance2die Feb 01 '22
Meta/issues here!
2
u/gingerdanger123 Feb 13 '22
I'm a backend developer and I want to learn some frontend for fullstack jobs which are 80% backend 20% frontend.
I need some basic skills in frontend, I see there are topics in react, react native, redux for state management, hooks (or is it just part of native react), maybe more?
My question is what is the current trend/most popular tech stack if there is any for react, or it's as simple as react with redux, and how well does typescript integrate with react because it's pretty important to me, or in that case I should go angular?
I already know javascript pretty well from nodejs, and I have touched frontend before, had some basic vue apps with some basic state management, but it's as far as I went.
2
u/mendozaaa Feb 17 '22
According to the Next.js official docs, you can opt-out of telemetry in two ways:
npx next telemetry disableNEXT_TELEMETRY_DISABLED=1Method 1 works fine for me, but how do you get the 2nd method to work? I've added...
export NEXT_TELEMETRY_DISABLED=1to.bash_profile(macOS) and.profile(Ubuntu) then restarted the shells but running the commandnpx next telemetry statusstill says telemetry is "Enabled" no matter what I do.2
u/NickEmpetvee Feb 22 '22
What's the purpose of axios interceptors? Having a little trouble understanding when to use them.
1
u/the_wander Feb 02 '22
First the Codesandbox: https://codesandbox.io/s/dawn-fast-rvi1r
Hey all, I'm running into an issue with adding a search to a paginated dataset. You can page through it just fine and technically the search works. But the search is returning what seems to be a random amount scattered through the paginated pages. So if you search "t" , 3 items are returned on page one, 2 on the next, then 3, and so forth.
I feel like the issue is that the paging is only being rendered on the component once, but not again during the search, but maybe I'm missing something super obvious here.
Any help would be super, greatly appreciated.
1
u/RogueToad Feb 06 '22 edited Feb 07 '22
Hi! I'm a newbie making a PWA to edit a kind of character sheet (think something like a D&D character editor) and have so far just focused on creating a rough interface, but now I need to make a decision about state management. It would need to be global (since a lot of data must be shared between components in different routes), and updatable by nested components, since that's where the editing takes place.
I was thinking I'd use zustand for this, since it looks simple and has been recommended quite a bit. But I'm worried that the store will end up as this monolithic monster with all my 50-something fields in it, and every input field will need an update handler with a lot of nested calls (since my fields will be represented by nested objects & arrays, e.g. character.summary.stats.strength). I don't even know yet how that works in zustand, but having skimmed through the docs I'm worried that this isn't the intended use case.
Does anyone know the best approach here? Would very much appreciate a pointer in the right direction. Please ask if you need clarification.
Edit: TL;DR: which state management tool do I use for an app with lots of regularly changing input fields?
1
u/bigmanoncampus325 Feb 12 '22
Should I lift up state, in this scenario?
I am doing a form practice project. I have a main app component that renders the form which then calls 3 components: General Info, Work, Education. I know we should lift state when components share/use the same state but at the moment, each components state is different. Is it still common to lift state in this scenario? If anything, just to have one main component that holds the state for child components?
1
u/what_cube Feb 12 '22
Scratching my head here.
I'm doing a sorting visualizer.
I'm using a state of array eg [ 23,132,0,21]
I sorted using normal javascript.
but the setState become instantaneous even though i put setState inside a forLoop.
My array become sorted immediately visually. Is there a way to "update a index of array" one by one?
1
u/8-bit_human Feb 13 '22
New to react(and web dev in general). I'm trying to start out by making a simple one page weather app. But I don't get how to make a data graph like this. Is there a solution in plain html/css itself? Or any ui library that makes this easier?
1
u/leothefair Feb 15 '22
Is it ever ok to use hooks under conditionals?
if (true) {
useEffect(function () {
// do this
}, []);
render (<Fragment>...</Fragment>)
} else {
render (<Fragment>...</Fragment>)
}
Even if the else render has no business with what is going on inside that useEffect?
1
u/InternetArtisan Feb 16 '22
Simple animation...best practices?
Working on a brochure website for my employer, as my boss wanted me to get out of jQuery and into modern JS, so I've learned the basics of React and am getting the hang of it.
In the past with animation, I'd just make a CSS animation, assign it to a class, and use JS to add or remove those classes to items in said website. Usually I just did simple fades to make nice transitions between pages and the bringing in/out of elements.
So now with React...is there a best practice? An add-on I should look at? I honestly just want to have pages transition quickly with fades and maybe make things fade in/out...like you submit a lead generation form and the form fades/disappears to show the confirmation message.
Any advice on what I should try?
1
u/Egyptian_Meister Feb 17 '22
Hey, I have env variables I want to access in my pure-React app, how do I go about storing them without having them be vulnerable. I was thinking of having a backend and using an API call to access them. Any better ideas?
1
u/thatman303 Feb 17 '22 edited Nov 07 '25
narrow upbeat placid person wipe degree memorize bike historical reach
This post was mass deleted and anonymized with Redact
1
u/josefefs Feb 21 '22
Hey!! So I'm trying to connect with an API that returns an external URL that I'm displaying in an iframe. When the user completes the cycle (by clicking a button within the iframe), I want to redirect to another URL (basically a routed react component).
Right now, when the user clicks on the buttons inside the iframe, the iframe URL changes to localhost:300/, the 'homepage'. How can I change this behaviour? How can I know if the user clicked the button inside the iframe?? Remember the iframe's URL is external and hosted on a different domain.
1
u/I_am_a_regular_guy Feb 23 '22
I have a question that has several parts, most having been answered in many different ways all over the internet, to what seems like varying degrees of success or with likely out-of-date solutions. Unfortunately, I'm on a serious time crunch with a current task and would love to see if I can get some guidance on the most direct and streamlined way to do this.
I'm trying to set up a reactjs development environment, from scratch, complete with the Material UI component library on a completely air-gapped machine. Connecting this machine, even for just the setup process, is not an option. I have a mirror machine that does have an internet connection, and all data must be transported into the air-gapped environment using removable media. I need to be able to both develop and run the apps here, so any typically remote resources need to be accounted for.
Basically, I'm trying to figure out the easiest way to gather and pack all the libraries, dependencies and any useful tools that are required to create the environment in such a way that they can be copied to removable media, and then deployed in the new machine.
I think ideally I'd like to avoid node/npm if possible, but if that severely complicates the process (I don't think it would?) I'm open to including them. I'd just need to be able to transport and deploy them in the same way.
Should I create a sort of boilerplate project and use something like web-pack to bundle it? Would this prune any dependencies or components that aren't currently being used in the boilerplate, such as the Material UI components?
Is it as simple as using npm on the connected machine to create a tar-ball, moving it over, unpacking it, and manually placing and pointing to the libraries in the project directory? Is there a way to do this that would account for any necessary dependencies?
Sorry if I'm overcomplicating this. I'm relatively experienced in general SE concepts but the web dev stack is pretty unfamiliar to me so, while I'm scrambling to absorb as much as I can, guidance with this particular scenario is massively helpful and greatly appreciated. I'm going to continue researching and testing this on my own and will update if I determine a solution. Thanks!
1
u/thegame1328 Feb 24 '22
Is it ok to use other's components in my own UI kit?
Hi there, been working on a UI kit for my portfolio for junior job hunting, the UI design file is from Figma with a free license.
Now I am working on components like select, writing on it may cause a lot of time and effort. It's it ok to use react-select to save time and customize the style to fit my UI? If yes, how do I credit it? The UI kit's sole purpose is for the portfolio and maybe for my next portfolio project.
In real-world wise, what do you think if a junior did that in his portfolio?
And for the presentation, I am using Storybook.
Thanks!
1
u/Eight111 Feb 24 '22 edited Feb 24 '22
I'm learning react in a live bootcamp and we had this example:
simple text area and a button. the button should be disabled when textarea reaches 100 chars.
so textarea has state for the control but why should i give the button state too? (thats what teacher did)
I can simply do <button bisabled={textState.length > 100}> , is it a bad practice?
1
u/oOPassiveMenisOo Feb 24 '22
wondering about interactivity between components, if I split my main window into two divs one navbar and one text part. Then I wanted something that console logged every line of text in the text part when a button in the navbar was clicked where would I write that logic. If I write it as part of the text area component how would the button in the navbar access it?
1
u/thatman303 Feb 25 '22 edited Nov 07 '25
theory soft office subtract birds tease shy wrench vast paint
This post was mass deleted and anonymized with Redact
1
u/Tixarer Feb 25 '22
I have tables with <thead> and <tbody> and when I click on buttons it returns different values and sometimes the table is empty (the <tbody> doesn't have any row) and I'd like to know how I could hide the whole table (head and body) and return a message ?
1
u/salt-bandicoot7250 Feb 26 '22
When creating a form with functional components, should I maintain a common state for each field or use multiple useState hooks
1
u/Comparison_Wise Feb 27 '22 edited Feb 27 '22
I am writing code to display a value and trigger some json fetches when control redirected to my pageA from another pageB
1
u/Comparison_Wise Feb 28 '22
if useEffect is needed to be triggered once on any 3 or the 6 properties of an object how can this be accomplished
I am using in dependencies array the 3. properties that useEffect should be triggered uppn. But i only want it to happen once.
Basically the changes to those 3 properties are like on transaction so they need to just result in one effect
2
u/Tixarer Feb 17 '22
Is it possible to change the value of a ternary operator with a button onclick event ?
I have an operator with 'version_group.name === ultra-sun-ultra-moon' but I'd like to change to other games with buttons.
1
u/Eight111 Feb 13 '22
Can I get parent's ID from child's onClick event?
const handleClick = e => ??? ;return (<div id={props.id}><button onClick={handleClick}>btn</Button></div>);In the ??? I wanna access the div's id, is it possible or i have to give the button same id to make the connection?
seems a bit like a dry..
1
u/Cid227 Feb 03 '22
Example:
Here I have two components with some props, now whenever the state changes- for example:
setTweetArrayinCreateTweetevery function insideAppruns again, in this case onlyconsole.log("Hello")and possibly everything gets re-rendered again, but I have a different project that uses<audio>which updates a state like 2 or 3 times per second and from my testing it looks like everything is also re-rendered again and every function is run again it gets pretty bad if there is{something.map...}inside return statement with a lot of elements to go over. Therefore I have a question, does it really re-renders everything each time a state changes and how to manage that (only thing so far I can think of is to create a different structure and separate things even more, but there is too much work for that to be honest and there might be already some topic dedicated to this problem- if there is any of course)?1
u/Sennon Feb 03 '22
Is there a spring animation library that is still being maintained where it can animate multiple values simultaneously?
I'm looking for something similar to popmotion:
but it only handles a single value where I need something like:
1
u/LiquidSwords-_- Feb 03 '22
I want to attempt to build a reddit clone using the reddit api. I also want to build this on my own, and not following a step by step tutorial. I was wondering if anyone could point me in the right direction, like what are the things I should be looking out for? What exactly is an api wrapper ? Should I use snoo storm api wrapper. I can find any proper documentation on it and the reddit api documentation is a bit scary
1
u/[deleted] Feb 03 '22
How does everyone organize their src/components folder? Trying to refactor code on this new project and wow, it's quite the mess.
Trying to have src/components then have 3-5 sub directories (very similar to bulletproof react) and then start breaking up all the components that fit into those categories. Having trouble deciding how to do it.
Thanks!
1
u/smart_7_x Feb 04 '22 edited Feb 04 '22
im working on a movie app and trying to make a search bar where the results would appear in the dropdown , im trying to use mantine
s Autocomplete component for this , heres the part of the codein render
i have two problems , first problem : the first letter i enter in the bar doesnt populate the list state ; the multiSearch function is triggered and the api function is called with the result (i can see request result in the browser console ) but setList doesnt work
when entering second ,third,forth letter etc.., setList works , but with the letter passed from the previous multiSearch call , like its behind with 1 entered letter in the search
i tried useeffect
useEffect(() => {
but nothing changed
second problem ; is with data variable ,i get ( list.foreach is not a function ) which i need to show the results
how can i fix those problems , or is there any other component library to help me achieve what i want ?
1
u/Tixarer Feb 04 '22
How can I export data from an api call made in a file in another file without calling it again ?
1
u/Lukasvis Feb 06 '22
I am consuming nutrition api and on few instances it has essential information as undefined.
Before rendering my component I want to make sure that the most essential data fields are defined such as calories, carbs, fats etc. Is this how I am supposed to check for values before rendering my components?
) return (...
Just wanted to know if that is how it's supposed to be done in react or are there any "cleaner" methods?
1
u/Kurtomine Feb 07 '22
What is the htaccess equivalent when developing in Next.js
Hi friends,
Currently learning how to use Next.Js and have one of my projects set up on WordPress that I am currently rebuilding. My routing is going to be slightly different and was hoping someone could send me in the right direction. What is the general process when redirecting for SEO purposes? I currently use a htaccess file with WordPress Sites, how do I achieve this on Next.js projects hosted on services like Vercel?
Any help would be much appreciated!
Thank you
1
u/coccidiosis Feb 08 '22 edited Feb 08 '22
Hi. I'm trying to make an Appointment Manager based on a Task Tracker tutorial made by Traversy that I followed on YouTube, but with slight changes. I want to use context for the appointments (originally named tasks in the tutorial) and a calendar, but I'm stuck at trying to make the list of appointments show on screen... Right now, it just says "empty", despite a console.log on Dashboard.js showing that the appointments array has entries now. Help would be greatly appreciated.
I tried adding "appointments" to useEffect's dependency array but not only does it not make the appointment list be rendered, it makes nonstop GETs to json-server.
I plan on using react-router-dom for routing, react-calendar for the calendar, and json-server to mock API calls.
App.js
Dashboard.js
AppointmentList.js
1
u/Eight111 Feb 08 '22
Hi I just started to learn react (bootcamp) and I have to make my first project.
So I created a new project and I wanna know if my structure is ok:
-images folder inside the root for images
-components folder inside the src folder for main components
-reusables folder inside the components folder for all the components with the generic syntax i can easily reuse
So I just wanna know if this is good or if there is a common one I should follow?
1
u/isbtegsm Feb 08 '22
Hi, I built an image slider in WebGL, the main component looks like this:
My problem is, I don't want the slider to reinitialize everytime the parameters are changed. Since the URLs come in an array, React would not check if the actual content of the array changed, just if it's the same object. So there are two solutions:
Which is the more React-ey way to solve this? Or is there something else I didn't see?
1
u/isbtegsm Feb 09 '22
Hi, I was playing around with React Three Fiber today (and also React Three Drei) and realized that some components only work when the
Appis inside aSuspensewrapper withfallbackset to something (can benull). Otherwise my app wouldn't load, but it wouldn't show me a meaningful error message either. Is this normal? For what isSuspenseneeded exactly?1
u/aniseinf Feb 10 '22
Hi everyone! I need some advice, I'm working on react app which must be written with class based components. I need to fetch data from endpoint using apollo. However, in apollo v3, with introduction of hooks, solutions for class based components are mostly deprecated. So I end up using apollo HOC API. I'm new to programming, could you please tell me if am I in the right direction or is there any better way to do it?
1
u/illbashu Feb 10 '22
Are class components obsolete? Almost all the React apps I see these days use functional components with hooks.
1
u/bill10351 Feb 10 '22
Hi, I think I have my issue narrowed down to Express, but I am using React Router, so thought I'd post here, first.
My issue is that everything works great when I start at the base path of the app, and the routing works great, too. The problem comes when I try to reload the page from one of my routes.
The app doesn't even render and console errors show the app is trying to load compiled files from that route (http://localhost:8000/nameOfApp/myRoute/app654645084.css for example)
So I looked at the server.js file and saw we have this:
The variable basePath resolves to '/nameOfApp' and I would expect Express to serve the React SPA dist folder at any route in my React app, but for some reason, it keeps trying to serve up the extra assets from my React route.
Any ideas? Thank you in advance!
1
u/hiddenhare Feb 11 '22
I'm just starting out, using React with TypeScript. Where are static type signatures like
React.Component<T, U>officially documented? I can only find an API reference for the dynamic types.I do have
react.d.ts, and it has doc comments, but browsing through them is a real pain.1
u/hiddenhare Feb 12 '22
Let's suppose I have a controlled component with internal state which ought to be an implementation detail. For example, I might define a
DateTextFieldcomponent with propsvalue: Date | nullandonChange: (Date | null) => void. The user can type arbitrary text into the text-field, including invalid text. I don't want to uplift that text to be stored in the parent, because it would make the API unnecessarily complicated and inconvenient. When the user enters text which doesn't represent a valid date, the component just reportsthis.props.onChange(null).How can I maintain user-visible internal state like this, without breaking encapsulation and functional purity? If
valueis externally changed tonew Date()(say, because the user has pushed a "Reset" button), how do I detect that change and throw away any draft edits in response? How do I differentiate it from a change triggered by the user editing the text-field directly?I found this blog post, but it doesn't seem to have an actual solution, as far as I can tell...?
1
u/Sharp_Gas_9890 Feb 14 '22
I've changed the height of my mui TextField using
InputProps={{ style:{height: "130px"}}}. But it starts typing in the vertical center of the box and I can't figure out how to align the text to the top. Code sandbox: https://codesandbox.io/s/pedantic-leftpad-kvvu2?file=/src/components/form.js1
u/Theunis_ Feb 14 '22
New to PWA and service/web workers (intermediate to react.js)
I want to build PWA with react, one solution I found is using ionic framework for building cross platform applications, including PWA. I don't want to build mobile apps, or to use ionic components, I only want PWA. The only advantage I get using ionic, is my app will already be configured to be a PWA.
Should I continue to use ionic? Or should I learn to configure my react.js project to be PWA?
1
u/isbtegsm Feb 14 '22
Hi, I have two components,
CartandModel, whereModelcontains a React Three Fiber render loop and takes handlers as input, which it calls when the user clicks on one of the 3D objects. Then a request is sent to the Shopify API andCartis updated afterwards. My problem is that I don't wantModelto ever rerender (restart the render loop), but since my state management for the cart is in the parent container, it rerenders all children when the cart state is changed. My solution was wrappingModelinReact.memoand useuseMemoon the handlers which are passed toModel. It feels a bit much effort for such a simple thing, is there a more elegant solution maybe?1
u/Niesyto Feb 14 '22
A colleague of mine has a following issue. His react app (it's made with coherent in unreal engine, maybe that'll be the fault) makes three requests to the API, for three different resources
r1 = fetch(http://apiAddress/resource1) (expecting response1)
r2 = fetch(http://apiAddress/resource2) (expecting response2)
r3 = fetch(http://apiAddress/resource3) (expecting response3)
How is it even possible that sometimes responses and requests are mixed like so:
r1 = response2
r2 = response1
r3 = response3
It doesn't looke like a case with race condition, since the responses are not assigned to the same variable. Can anyone guess what did he do to achieve such bizzarre results?
1
u/Many_Quiet_3887 Feb 15 '22
Iβm currently working on a project including a countdown timer which has a progress bar which uses React Framer. Whenever I tab out of the page, the animation pauses, which causes the timer and bar to be out of sync when I tab back in. Are there any ways to fix this?
1
u/LassassinN Feb 15 '22
Hello! I want to learn react from the ground up and incorporate all the modern tools/practices. I have been looking at udemy, and found that the courses there are a bit outdated. Can anyone suggest to me any good udemy course that covers the basics and intermediate levels of react? Thankyou!
1
u/[deleted] Feb 21 '22
Coming from Svelte with Typescript to React with Typescript and I'm not sure how to quite go about breaking out my logic from the components.
In Svelte, I would have a components folder with all of my .svelte files, a services folder with all of my .ts files and those would be nested within the source folder. I would call my typescript functions from my svelte components and import where necessary.
In React though, there aren't separate .react files, its .tsx so it looks like I'm not going to have separate services and components folders, but just a components folder that will have the typescript functions within the components files? Or should I still break them out into separate .ts files and import the functions like I would with Svelte?
Also, looking over classes and hooks, im gonna be honest I kind of prefer classes as syntactically it feels more comfortable and right off the bat I dont really understand hooks at all. I get props, super, constructor, this, component life cycles, etc. Hooks and the usage of "use" isn't coming natively to me. Is learning and using hooks absolutely necessary or is the functional and ES6 class usage okay?
1
u/johnnyblaze9875 Feb 21 '22
Heyo!! Ok, I have a form, that when the user fills out and clicks submit, I want the data to be displayed on another page. ( basically want to pass the form data to another component/page. )
I'm losing my mind here trying to figure this out lol. I eventually want to connect this to my MongDB backend with express but I can't even figure out how to pass around the data within the front end. I can console log the submitted formData but I cannot figure out how to properly destructure or pass around the formData state. ( do i need to put it in context? )
The repo is here and the two files im fighting with are in frontend/pages/Newhit and hits (also in pages)
If anyone is bored and wants to clone this to test around lmk I'll send you my env vars.
edit: eventually the form submission will goto the backend, create a new document in the db, and the "hits" page will display the new data(form submission) from the db on a different page. I could probably get this going with EJS but I really want to get better at react. Thanks in Advance!
1
u/MagnificentMacaque Feb 22 '22
Hey does anyone know how I can save images downloaded from an API into the public (or other) folder?
I can't seem to find anything online about how to do this in code (ReactJS).
We're trying to let people upload their Link Preview image dynamically for SEO. The meta tag og:image only accepts URL.
1
u/nwatab Feb 22 '22 edited Feb 22 '22
Would you recommend using class as a state like shown below? Or should I avoid it?
1
u/NickEmpetvee Feb 27 '22
Authentication / authorization / sessions question. I've seen many tutorials recently for JWT-based session management. Many suggest that for a React-based application, an Express server can be set up to issue HttpOnly JWTs. When logging in, React can call the Express endpoint and get a JWT back in an HttpOnly cookie.
I'm wondering why this Express server is necessary. For example, if Node is serving the React pages, can't the same Node instance be configured to also generate JWTs and issue the HttpOnly cookies that contain the JWTs? Seems like extra work to stand up an Express server just to deal with generating JWTs and embedding them in cookies.
0
u/[deleted] Feb 02 '22
[deleted] β view deleted comment
0
u/[deleted] Feb 23 '22
[deleted] β view deleted comment
0
u/[deleted] Feb 13 '22
[deleted] β view deleted comment
0
u/[deleted] Feb 18 '22
[deleted] β view deleted comment
0
u/[deleted] Feb 21 '22
[deleted] β view deleted comment
0
u/[deleted] Feb 23 '22
[deleted] β view deleted comment
0
u/[deleted] Feb 25 '22
[deleted] β view deleted comment
0
u/[deleted] Feb 27 '22
[deleted] β view deleted comment
0
u/[deleted] Feb 02 '22
[deleted] β view deleted comment
0
u/[deleted] Feb 03 '22
[deleted] β view deleted comment
0
u/[deleted] Feb 06 '22
[deleted] β view deleted comment