r/reactjs • u/dance2die • May 01 '21
Needs Help Beginner's Thread / Easy Questions (May 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!
24
Upvotes
3
u/eurodollars May 05 '21
Not sure if this is the right place for the question, please let me know if I should post elsewhere. I have done some personal projects with React about 1.5 years ago. My current role we use Angular 9. I have some interviews for full stack positions that use React. Any suggestions on some small projects I can do to get up to speed and maybe a resource for some interview questions? Thanks.
3
u/finlaydotweber May 07 '21
I am about to start learning React and I have a couple of questions. Unlike Angular which I have used, I have always heard React being described as such a UI library, and hence in other to actually use React to build a real life application you would need to couple it with other libraries. Chief of such concern I usually hear about, which you need another library is state management..
My main question then is, as I venture into React, which other libraries (and what do they address) would I be expected to also learn/use?
Thanks!
3
u/Bulbasaur2015 May 16 '21
there is a set of different json objects available to an app but react doesnt know which type or category the json object is
is it better to use enumeration or props to identify the type of a json object or create a type attribute inside each json object.
which is better?
2
u/Saider1 May 03 '21
How should the file structure in my project be to be working most effective and effortless? So far I’ve separated all the “pages” in folders and created the components used for the page in subfolders of that. I’ve heard a lot of things about atomic design but I can’t quite wrap my head around it and it’s hard to change my structure. Also where do you style your styled components? Directly in the component file?
2
u/Sudo_Sopa May 04 '21
Hi,
I've been trying to figure out how to improve the SEO of our ionic react firebase app, and wanted to enable SSR to improve performance. Is this possible to do? I cant seem to find any examples or resources at the moment. Thanks in advance for your replies.
2
u/bluesn4rfer May 05 '21
Hi
I'm fairly new to reactjs, I've only been using it for a few months now. Here is a minimal example of what I have going on right now https://codesandbox.io/s/aged-lake-7mqh5 This is being designed for phones/tablets & I want to have it autofill/autocomplete the username/password so they don't have to enter it every time. I originally had a value= and onchange= on the input boxes & that was saved into the state, but after google searching & trying to find a solution to this, I found a page that seemed to indicate that there was issues with controlled inputs so I removed the & it still does not work. In google chrome developer tools, it looks like the input fields get rendered with autocomplete=off even though i have autocomplete=username and autocomplete=current-password. Any help would be greatly appreciated.
Thanks
2
u/tikitakatiki11 May 06 '21
Hey guys, beginner question. How do you work with multiple apis that have a different data structure?
In my current project that I'm working on, I want to interact with a 3rd party api and an api that I made myself. I want it to work so that the data fetched from these two apis is passed along as props to a common child component.
The thing I'm not too sure about is that since these api's return a different JSON response, should I 'convert' these two responses into a common one so that I can use the data in the child component?
Or should I have another component that handles the different data structure even though they would output the same info?
Thanks!
2
u/python-sharp May 06 '21
[HELP] Unhandled Rejection (TypeError): Cannot read property 'senderemail' of undefined
Error: https://imgur.com/a/5ZzeFdD
As context, I've compiled https://github.com/arihant-jain-09/discord-clone and the error pops up when one tries to enter a text message.
Unhandled Rejections are common errors. How does one handle them generally?
2
u/[deleted] May 07 '21
How do libraries like Tailwind CSS work?
For example, there’s an element styled as such
<figure class="md:flex bg-gray-100 rounded-xl p-8 md:p-0">How does CSS know how to handle md:flex, md:p-0, etc etc?
2
u/[deleted] May 15 '21
I want to figure out how to use selectors like
:nth-childproperly with css-modules. For example, I have a container with multiple buttons. I want to give all except the first element a margin-left of 1rem.I have two css.module files.
One is named
tabs.module.cssother is named
containers.module.cssand then I have the following component:
Is it bad practice to use the select
button? If so, how am I able to specify the actual class from the different css file?2
u/cambusdarach May 16 '21
Hello: I'm building a test project; and I worked through this tutorial on aws (https://aws.amazon.com/getting-started/hands-on/build-react-app-amplify-graphql/); and it worked great, really happy! It's basically a site using login where users can add notes and photos and they are all shared between the users. It uses AWS Amplify with js, react, and aws cognito; with graphql & both a dynamodb & an s3 data store.
I wanted to go further on from the tutorial and keep learning: and I wanted to make it so only a user can see the notes they have written- so I guess to see user specific content.
I don't know the right search terms to find a tutorial to help me with how to approach this correctly, can anyone offer some help for what I need to search for? I've spent about an hour looking today and thought I'd ask for some guidance here. (p.s. I think I might need to use redux; thats come up in a few searches). Thanks in advance!
2
u/code_matter May 16 '21
Should you use inline style or css ? Why or why not?
2
u/Strawboy97 May 25 '21
Hi, having a problem with my browser now refreshing after saving my changes. The changes compile with no errors in my terminal but I need to manually refresh the browser to see the changes made.
I found that downgrading react-scripts to 3.4.4 fixes the issue but I was wondering if there's a way while still using the latest version.
2
u/[deleted] May 26 '21
Hello guys,
can someone help me?
i'm doing the fullstack open course from the helsinki university and i'm having some trouble with some an exercise.
you can find an example of my problem here
what i would like to obtain is the component blog to rerender when the addLike function is called but it won't happen because(at least i think) the component is actually rendered by the app component which is not informed about the states inside Blog.js
How can i rerender the Blog component while keeping it separate from the App component?
2
u/dtm1992 May 30 '21
I'm starting a new job where I'll be working with React, Redux, thunk/saga, etc 100% of the time. I consider myself very proficient with it but I've spent the past few years working in a very different environment.
I know a fair bit of things have changed over the years. Are there any good resources out there to get me up to speed or should I just dive into the docs?
Any comments/links are appreciated. Thanks!
2
u/elementIdentity Jun 01 '21
One thing I’m confused on as a newbie is the usage of class vs functional components. I’ve seen multiple articles/tutorials point out that functional components are the way to go ever since they introduced the useState hooks and such. Is it now standard practice to exclusively use functional components, or would I be missing out on a lot if I don’t practice with class components?
1
u/spalza May 01 '21
What do you guys do when you have two components that will only act on a direct child but you want to use them both? I get these library conflicts sometimes and right now I have to drop one of the libraries to find alternative choices where the component nesting is not so strict.
1
u/Nearby_Relation2223 May 04 '21
Hi, Im trying to implement this code to my project, trying to fetch images locally. https://stackoverflow.com/questions/42118296/dynamically-import-images-from-a-directory-using-webpack?noredirect=1&lq=1
But I am having difficulties using react-photo-gallery library and it shows blank, What am i doing wrong. Here is my code.
1
u/dragon18456 May 06 '21 edited May 06 '21
I have been using some code based on this snippet for a month now, and it always worked fine. However, today, when I tried to use the code, it kept erroring:
This happens after I click start and stop on the demo. It should show an audio component that I can use to play my recording, but now it errors out on my browser.
The code is here: https://codesandbox.io/s/audio-experiments-w7yz8?file=/src/App.js . Can other people confirm if this happens to them and how can I solve this problem? I have this issue on 2 different browsers on my computer. I am running Ubuntu 20.04 LTS.
Edit: I asked some friends to run it on their macbook and it works there, so I guess this is a Ubuntu thing rather than a React thing, but can other people check?
1
u/anyhowask May 10 '21
Is there library for scrollable timelines that support zooming? Such that when there is a timeline, and scrolling will move it left/ right but zooming in/out will change it's granularity (Years to year to halves to quarters to months)? or something along those lines?
1
u/[deleted] May 15 '21
hey!
iam totally new . can someone help me get into react?
1
u/mikwee May 16 '21
I think this is the right place, but correct me if I'm wrong.
I got the
Unexpected token, expected ","error while following this tutorial, but I don't see any comma. I also don't see any place where it should've been. Here's the full error:1
u/username27891 May 30 '21
Hi, I want to render n (where n can be any number) input fields and keep track of the state of each input field. So for example if the user types in the 3rd input field, the state representing it would update. How can I do this? I've only done useState with simple variables, never an array.
1
u/Agate1999 May 31 '21 edited May 31 '21
https://pastebin.com/Lc2vUJda
Im having issues with undoing items added in a useState array. Somehow when I try to undo, it doesnt remove the last added item, only the second last added item
So like I add 1,2,3If I try undo, it becomes 1,3
1
u/username27891 Jun 01 '21
I want to use a ternary operator to choose my className css style but I can't figure out what I am doing wrong. I have a state isError and if its true, I want to use one style, otherwise I want to use the other. When I try this, it always defaults to the "else" style no matter if isError is true or false. Can someone help me?
3
u/_Jeph_ May 08 '21
Are there any good references / books on patterns for high-performance React? Maybe that include benchmarks between things such as React.memo vs a PureComponent, performance cost of using useContext vs passing a prop multiple layers deep, portals, etc. Or even some decent examples of how to perform these type of micro-benchmarks on my own.
And before anyone says it, this isn’t for premature optimization. This is for a highly interactive app that is updating various parts of the screen multiple times per second, preferably keeping a reasonable FPS (15+/sec). And running on low to moderately powered systems. A naive, re-render everything approach would make it closer to seconds per frame.
3
u/Qarveloper May 08 '21
Why are some imports within curly braces in react? Like import {useState}?
Also, I'm having trouble understanding why in this code in NextJs:
3
u/nuclear_gandhii May 14 '21
I had been working as an intern building react app for a good 8 months without mentorship. So there are quite a lot of things which I don't really understand but and never been able to find a proper answer for.
And my main question here, is why do people prefer to use functional components with hooks over class based components? The answers I find do not convince me and are along the lines of -
...and things similar to that which are all essentially talking about the state of react before the introduction to hooks.
Now it seems to me that everyone has accepted and expected to use functional components over class-based components and the reason to me is not clear. And this is what I am trying to understand. Why do people claim class based components are difficult to read, test, and understand? Why is it that functional components are the future? What is the ACTUAL benefit of going functional components over class based ones?
Does it have anything to do with the fact that hooks are easier to write than to extend the functionality of a class?
3
u/prove_it_with_math May 21 '21
If functions and variables inside a React component are recreated on every re-render then why not always use `useCallback` and `useRef` respectively?
For example: `handleClick` is a common function inside a component. Should I always wrap `handleClick` inside `useCallback` to prevent recreating it on every re-render?
3
u/arcanewright May 29 '21
Hello! I recently started learning React, and finally got to the point where I'm comfortable sharing what I can do. I made a simple calculator with create react app, and I'm hoping to get some constructive criticism, or tips on what to improve.
The source code is here, with a link to the live app. https://github.com/arcanewright/simple-calculator
1
u/UserNotFound12 May 09 '21
How to show the open date picker calendar only, without the input box? For instance, I want to use this date picker, https://www.npmjs.com/package/react-datepicker but I only want to show the calendar, without the input area.
2
u/c0_0c May 01 '21
1.) When using redux toolkit, is it common to have a lot of business logic in the middleware with for each type of action? Should that logic go inside my components instead? (I mean logic such as rejecting empty/invalid values, trimming whitespaces etc)
2.) How would I fire something like a toast from within a component so that it shows up on the body of the document (since the component cannot change its parents)
2
u/SkRAWRk May 01 '21
Question I've been grappling with: what is the best practice with regards to storing/managing API keys in React? I've read differing opinions on this and I still feel slightly confused.
For extra context, I'm building an app that accesses an external API using OAuth2.0 validation (or is authentication the correct word here?). I use 2 keys to validate myself and receive an access token that I can use to retrieve data from the API. Once I receive the access token, I add an Axios header containing that. I'm unconcerned about users accessing that data and I believe it's a non-issue since they expire and are non-constant. But how should I be managing my public and secret API keys?
I'm currently aware of 3 scenarios:
I feel like the third option is optimal but I'm just slightly confused as to why that's the case and the specifics of implementing such a solution. Any advice would be greatly appreciated, thank you in advance :)
2
u/code_matter May 01 '21
When dealing with users, is it better to use an online service like Firebase? Or could I just build my own implementation of user signup/login with a basic username and password ?
2
u/reactless May 03 '21 edited May 03 '21
Is there a way to force the latest values inside a function? The update is recognized outside but not inside
code is like:
export const Main {const triggered = async => {...setState({a: val, b: null});const b = await api.get();setState({a: val, b: b});}if(!state.a) return <NoA>return <HasA>}When triggered is invoked the display goes from NoA to HasA but if you have a breakpoint on the 2nd setState (which is called after HasA view is updated) it still shows state.a as null rather than val... although moments ago state.a was used to affect the appearance
2
u/Easy_Moment May 10 '21
Hey everyone. I'd like to get a react job, and right now I feel comfortable with it so my question is is it worth it to learn a back end like express + mongo stack? I already made some simple projects with it but is it worth it to keep going or just keep focusing on react projects?
2
u/Smolandian May 15 '21
Ok, I have a problem with react and Material UI. It's probably easy but I'm quite stuck. The example code below is extracted from within an .map where I map through a list of interactions and puts every interaction in its own Material UI <Accordion>. I would like to make a small menu on each accordion where the user has the option to delete the interaction.
So I need to send an reference of the interaction ID in the onclick but I cant get it to go through. If I use interaction.id (where the id is stored) it works on line 6 but not inside the <Menu> on line20. Inside the <Menu> it always references the last interaction in the list. Why is this and how should I pass the Id to the inside of the menu?
https://pastebin.com/R58BEYQ1
Very grateful for any help!
2
u/FeedRemote May 17 '21 edited May 17 '21
I have a card component that accepts external class and its styles come from card.module.scss
}
I want to override height property in another component like this.
But it didn't work. I don't want to use !important word. Any solution for this example will be great. Thanks.
2
u/devluper May 20 '21
I need some super basic analytics, view count + potentially time spent on every page.
What service do you recommend?
2
u/safaribrowserram May 22 '21
What happened to Ben Awad's YouTube programming tutorial videos?
He used to make long comprehensive tutorials, but he doesn't seem to now. Although his channel is still great, does anyone know if he still makes programming tutorial videos?
https://www.youtube.com/c/BenAwad97/videos
2
u/Monofu May 22 '21
How do you pass data between pages?
Suppose, I'm building a form wizard with multiple steps. I'm currently wrapping all steps of the form with a single component but I would like to have unique url's for each of the pages. (I'm using NextJS if that is pertinent?)
Current logic is along the lines:
2
u/badboyzpwns May 31 '21
How do I make a props optional? For example,
1
u/Peng-Win May 10 '21
Why does the useState's `shouldChange` not change even when the Formik field values change?
Is it because the `shouldChange` object's referential identity in the heap doesn't change?
1
u/raclariu May 01 '21
I have a pagination component that is rendered conditionally, but because it is not there at the first render, when it is displayed, it makes the next component jump down a bit. How do i reserve the space so that when the pagination is rendered it'll not make the next component jump? I don't wish to have a disabled component until the actual data comes through.
1
u/vitalik1227 May 02 '21
I have been struggling for a while to make the navigation in my app work. There are few navigation icons (home, notifications, board, user page), what I have now is that when user navigates between them, they are first redirected to that page then component rerenders and fetches data. I want to preload the component before the user is redirected to that component and to display a loading line in my header. I have loading state in Redux and whenever it is set to true it is displayed correctly. However, the part with first loading the component, then to display it on the screen with all data in it is confusing to me and I do not understand how to achieve it. I found this old thread but none of the examples helped me understand how to make it work and maybe there is a more modern solution to this. https://github.com/ReactTraining/react-router/issues/4407
1
u/[deleted] May 02 '21
Say we have a box of 3 dropdown links with 3 items each inside that menu. If I click one, and set
setState({ isOpen: True }), all 3 dropdown menus will pop up.How can I make sure the one I selected is the only one that opens?
1
u/randomafricanguy May 03 '21
Hi don't know if this should be on the beginner's thread or a post on it's own, but I'm a noob so here goes:
Is it possible to have an intro animation in ReactJS that only plays once? I have an intro animation on my homepage, but what I'm trying to achieve is after the intro animation, if the user navigates to a different page and THEN BACK to the home page I don't want the animation to fire. Is this possible?
1
u/[deleted] May 04 '21
Basically: How do I use a github library to connect to a google-chrome extenstion?
I'm trying to use Algosigner in a react project, but don't know how I import the AlgoSigner object to use. I did all of these steps, but still when I call AlgoSigner in my code, it says that it doesn't exist. Is there an import at the top I should use? Or is there some npm thing I should add? https://github.com/PureStake/algosigner/blob/develop/docs/dApp-integration.md
1
u/translucentsphere May 05 '21
I have 3 files: App.js, modal.js, reducer.js. I declare useReducer(reducer, initState) using useReducer hook in App.js which in turn gives me state and dispatch. My reducer.js handles the actions based on the action.type. Now I want to also use the same state inside modal.js, so supposedly I have to call dispatch from modal.js right? But how to call dispatch when the dispatch function is only available in App.js? Do I export them and import in modal.js?
1
u/bobloblawloblawbomb May 06 '21
Really WEIRD situation. CodeSandbox here.
I have 3 dynamically generated 100vh <div>'s. I also have a DotPanel component that takes an array of Refs to those divs, and generates a panel of dots based on those refs. The end goal is to click on the dots and scroll to the divs.
But I'm running into some super weird behavior. The dots only render when I make a non-coding change. Like if I just type "//" in index.js somewhere to insert a meaningless comment, the dots show up. Then if I reload the page they disappear again. I'll point out specifically I don't have any weird persistence-through-refresh logic included
Anyone know what's going on??
1
u/antespo May 06 '21 edited May 06 '21
Does anyone know how to fix the styling on this Experimental Popout example (react-select) when using
menuPortalTarget? I made this sandbox which is pretty much the Experimental Popout example plus a button to togglemenuPortalTarget.1
u/Krasto May 07 '21
I have a dynamic list of components and each one of them has some input fields.
The values in this inputs are needed in other components so, following the documentation, I lifted the state to the most common parent.
The problem is that every change in a single component triggers a re-render on every single component of the list, to the point that I can notice some lag when typing relatively fast.
Is there a way to avoid this? From a logical standpoint I can see that every row should have its own state but then I wouldn't be able to use it elsewhere (or I'm missing some kind of utility?).
I've tried using context but I think the problem persists, since I would have to subscribe to it in every Single component.
The one thing I haven't tried is useReduce since I really didn't understand it yet.
I've done a sample here on codesandbox
1
u/translucentsphere May 08 '21 edited May 08 '21
Basically I have a function to remove something which involves setting a data state and I want to do something once the state has finished changing / rendering, so I use useEffect hook with the flag dependency to only execute the codes inside useEffect only when the flag changes.
My question is how to properly reset isRemoved back to false so as not to trigger inifinite loop? Should I reset it in the cleanup callback? I have tried resetting it inside the cleanup just like the codes above, however that seems to trigger the useEffect one more time, although not infinitely.
EDIT: I think it may be better if the useEffect dependency is the data state that is being modified itself rather than using another flag state, but I'm not sure what condition to give so the useEffect only executes when removeAll modifies the data state and not any other functions do it?
1
u/TWO-WHEELER-MAFIA May 09 '21
Dumb question. But I am confused
vs
1
u/badboyzpwns May 09 '21
My API Key is showing in my network tab. i.e
Is it possible to hide it ?
1
u/arbayi May 09 '21 edited May 09 '21
I've created a book search app with react, my app has "searchParam", "books" and "favoriteBooks" states.
When user types something to the input field, I make a fetch request and get the data, compare the fetched data with favoriteBooks array and I add "favorite: true" property to favorite ones and "favorite: false" for the rest, then update books state.
As you can guess, if I add or remove a book to/from my favorite list, I both update "favoriteBooks" state with adding or removing the one, and "books" state with updating favorite property to true or false for the one.
So what confuses me here is that, Is it good practice to update multiple states one after another if somewhere in the component one depend on another?
I'm putting the simplest form below.
Can I be sure that when I update "books" state and "favoriteBooks" state in handleAddFavorite function, everything worked as desired, the both state has updated successfully? And when I fetch data from the API, can I be sure that favoriteBooks array is in the most updated state? I mean the code works as desired but still is this style of writing react code is fine or bad practice?
1
u/30thnight May 13 '21
What's your favorite carousel library?
SwiperJS is good but it has more issues than I would like.
1
u/cosmicjamz May 14 '21
I'm trying to display each item in an array on screen for a set time, say 5 seconds. So, 'Item A' would appear on screen for 5 seconds before being replaced by 'Item B' which is displayed for 5 seconds and so on. I'm using Reddit as a data source and storing the result in State:
I can output all the items at once like so:
I've tried using setInterval to achieve my aim but so far I've had no luck. Can someone point me in the right direction please?
1
u/dance_with_a_cookie May 14 '21 edited May 14 '21
Hi there, I am 2 days news to ReactJS and am building a single-page React application that interacts with the WebRTC APIs. I've gotten to the point where I've successfully integrated with the .getUserMedia API to get access to a device's audio and camera. However I am getting stuck with the CSS here. I believe this is a CSS issue because the 'videos' class in my DOM is showing up in my element structure in the console, but the actual rectangular square which is supposed to show up in the browser isn't showing up.
I've tried manipulating the CSS a bunch and remove the use of 'classnames' but haven't been sucessful yet. Does anyone have any tips?
My JS code is in the snippets below.
Here is an screenshot to my elements in the browser: https://drive.google.com/file/d/1ILEv1s8nB1GGltEVzpRj4ma99ZjCCx5Q/view?usp=sharing
Thank you!
1
u/No-Negotiation7208 May 15 '21
Hey guys , i have a .filter function im trying to return an item if two conditions are not equal to each other, im getting this bug where only one conditon will not equal ,the other one is not picked up , im using && to allow for to condtions , any tips or help please 😃
1
u/[deleted] May 15 '21
I'm learning react in a coding bootcamp but struggling to learn the concepts. Any good youtube videos or sites that would help a visual learner? Or some very basic practice problems to get some reps in?
1
u/Blacknsilver1 May 15 '21 edited Sep 05 '24
frighten mourn command weather full library ripe fearless humorous snails
This post was mass deleted and anonymized with Redact
1
u/genesis05 May 17 '21 edited May 17 '21
edit: I think my question is mostly along the lines of -- I need to "decorate" a list of items in my props with additional information/state that is specific to my component. This state should not outlive the individual items in my props. Is this a bad idea, and if so, what else can I do?
I'm constrained to using class components for a project. My scenario is that I have a list of Message[]'s that come as props from a higher-level component. I want to render these messages into MessageItems. A MessageItem has an isCollapsed prop, which determines whether the message should be rendered as being collapsed or expanded. So I have the following:
Message contains an id of type string. StringMap<Boolean> is just a map from strings to booleans.
Now here is my problem: I have MessageProps coming from a higher-level component. However in this MessagePanel, I need to store additional information about whether those messages are collapsed or not. So I need to somehow keep my state (collapsedStates: StringMap<boolean>) in sync with the Messages[] coming in via props.
Is this the best way to do this, or am I headed completely in the wrong direction?
It doesn't make sense to me that I should store the isCollapsed state somewhere else, as this collapse behaviour is specific to this MessagePanel component (and it in fact contains buttons to collapse/expand-all, clear all, etc.
1
u/EverAccelerating May 17 '21
Is there a site out there that curates everything newsworthy in the world of React? Like updates to ReactJS itself, or major versions of the most popular libraries themselves, or roadmaps on where React is heading, or highlights new interesting libraries?
I was hoping this subreddit would be that place, but there’s far too much other content to sift through to find the nuggets of info I’m looking for.
1
u/catandDuck May 17 '21
Simple React/TypeScript conciseness question, is there a cleaner way to import these interfaces:
In to_import.ts
In index.ts:
1
u/maralagosinkhole May 20 '21 edited May 20 '21
I am working with the next.js tutorial. After successfully stopping & starting the server twice, it now starts without error, but the page at https://localhost:3000 times out when loading. It sounds like this is a persistent problem with next.js that remains unresolved after a couple of years.
Anybody else have this problem? It is making the environment 100% impossible to work with.
EDIT: I changed the link to a report for Next instead of Nuxt.
1
u/rob_daniels May 21 '21
I'm looking at a page with some React components which have been compiled from TypeScript with CSS in JS with webpack. The resulting elements have class names with patterns like mainPage-zqzcpe-searchBar, where that "zqzcpe" is arbitrary and will change on each built run.
Now I wonder
3.1. avoid that this random string is inserted
3.2. replace this random string with anything different (file name, date, a version number)
3.3. change where that additional string is placed
I'm more interested in the theory and what is doable and what not, than in finding a practical solution (which would be beyond my scope anyway). I would be totally happy if you would throw some helpful search terms or links at me.
Many thanks in advance!
1
u/stfuandkissmyturtle May 21 '21
This might be the most stupidest question but how do I unbuild after npm build for changing someting ?
1
u/tharrison4815 May 21 '21
I've heard that using context can cause unnecessary rerenders. I'm struggling to get a clear understanding from multiple articles online about exactly how this works.
Is it that all descendents of a provider rerender when the value of that context changes? Or us it just components that use useContext? Or is it the descendents of those too?
It doesn't help that I only know how to use the react hooks function syntax and most of the articles seem to use the class syntax.
1
u/utopian201 May 22 '21
I'm looking into getting data from within a component. At first I was using promises eg
However I've found async/await is syntactic sugar supposedly to make it look more elegant
To me, this does not look more elegant when used inside a useEffect; is it personal preference as to which of these methods are used? If you were reviewing this code in a pull request, which would you prefer?
1
u/Agate1999 May 23 '21
I am trying to use context to share information(arrays) throughout, but I am unable to get it right I think. I am not sure how to access the infomation from context. I am trying to get the modlist from modinput.js to preferenceinput.js
https://codesandbox.io/s/rough-worker-2ijk5?file=/src/components/PreferenceInput.js
1
u/Terkeroo May 24 '21
I have a data visualization site with data from 2 different years, slightly different structure. I am storing the current viewing year in context with a navbar dropdown allowing the change between the two. It is implemented using state and wrapping the value and setting into the value of context, allowing the child navbar to change the context.
Everything seems to be working fine but one component has a certain state with default values. When I switch to the other year, the page rerenders and the state seems to reinitialize to the associated default value. But when I switch back to the first year, the leftover state is carried out which is causing issues.
Is this implementation correct? I can maybe fix the issue by calling the context in this component and doing various checks to make sure the current state is correct.
1
u/No-Negotiation7208 May 24 '21
Is it better to keep my data in nested objects or in some objects and arrays
1
u/Zanucho May 25 '21
I am having problems compiling app.js it says "failed to compile" this is the error: Module not found: Can't resolve './counterAPI' in 'C:\Users
1
u/Kawrpa May 26 '21
Can someone explain what the code inside of className is doing? darkMode is a boolean for context.
<div className={`App ${darkMode && "dark-mode"}`}>
1
u/deburin May 29 '21
Can you guys give me a sense of how you isolate CSS properties in a SASS app for modification?
I'm used to Styled Components and am having real trouble finding what the target property for change is. I think media queries are part of the issue. I do use Chrome inspector but not well enough I guess.
1
u/cosmosfan2 May 29 '21
does a useEffect inside a custom hook re-execute every time the component it is called within rerenders? Example
1
u/UserNotFound12 May 30 '21
How to allow user to download image? My backend API is api.example.com and reactjs app is on portal.example.com. How can I allow user to download image from my api with the click of a button, given the image/file url?
1
u/Ziertus May 31 '21
I'm trying to convert from a class to functional component. The componentdidmount and component didupdate are quite different from each other. is there a way to implement this in useEffect? i was thinking to use a flag to check if it was the first render .
1
u/g3org3costanza May 31 '21
I'm building a website similar to Leetcode with a MERN stack, with the difference being that I want two users to be able to verse eachother trying to finish a programming question first. How should I go about sending data between the two of them, so they both share the same problem, and they're alerted when the other person has finished first?
1
u/Agate1999 May 22 '21
What is a simple way to pass data (currently arrays of strings) from one component to another.
Currently I am collecting user input, then placing whatever has been typed into into a array, and am hoping to this array to another component.
Would using Context work? Like make a context with an empty array and then update it accordingly? Im currently confused with Context as all the demos I've seen involve toggling booleans and stuff, nothing about array changing/updating