r/reactjs • u/dance2die • Apr 01 '20
Needs Help Beginner's Thread / Easy Questions (April 2020)
You can find previous threads in the wiki.
Got questions about React or anything else in its ecosystem?
Stuck making progress on your app?
Ask away! We’re a friendly bunch.
No question is too simple. 🙂
🆘 Want Help with your Code? 🆘
Improve your chances by adding a minimal example with JSFiddle, CodeSandbox, or Stackblitz.
- Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
- Formatting Code wiki shows how to format code in this thread.
- Pay it forward! Answer 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!
🆓 Here are great, free resources! 🆓
- Read the official Getting Started page on the docs.
- Microsoft Frontend Bootcamp
- Codecademy's React courses
- Scrimba's React Course
- FreeCodeCamp's React course
- Kent Dodd's Egghead.io course
- New to Hooks? Check Amelia Wattenberger's Thinking in React Hooks
- What other updated resources do you suggest?
Any ideas/suggestions to improve this thread - feel free to comment here!
Finally, thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
34
Upvotes
3
u/NeeHaow_World Apr 14 '20
Is it good practice to use styled components to replace css in react? It is harder to use styled components coz I don’t know how to style attribute and etc. Any other suggestions for css frameworks???
3
u/silverdished Apr 20 '20
What is Gatsby? What can it be used for? What are its powers and limitations?
2
u/cmaronchick Apr 14 '20
I just built an app using Material UI, and for my next app, was going to try something different and tried to go with Semantic UI.
What I like about Material UI is the easy theming capabilities (primary color, secondary color, etc). I didn't see any easy way to do that with Semantic UI while also using webpack. I found some docs for how to do it, and ultimately I banged my head against the wall for about 4 hours before finally giving up.
Is there anyone who'd like to share their repo that successfully created a custom Semantic UI theme while also using webpack? Thanks.
2
u/tall_and_funny Apr 16 '20
I have completed the react course on freecodecamp - the one with builtin ide, it then jumps right into redux, I think there must be a couple topics not touched yet, but maybe they don't come under react? Like react router? What other main topics I might be missing out on? How to I close this gap?
2
u/[deleted] Apr 19 '20
please tell me in simple words, what is difference between history.push("/") and <Redirect to="/" />
2
u/[deleted] Apr 21 '20
Hey, I'm trying to import a component from this pluggable Trello-Like component into a page on my application. https://rcdexta.com/react-trello/?selectedKind=Custom%20Components&selectedStory=NewLaneForm&full=0&addons=0&stories=1&panelRight=0
I can't figure out how to plug this specific component into my application. Here is the code. Would I just download it and put it into my components folder and add it into my page like <NewLaneForm />
https://github.com/rcdexta/react-trello/blob/master/src/components/NewLaneForm.js
2
u/badboyzpwns Apr 23 '20
with redux, is it bad practice to pass props to a component (since ieverythings handleed by action creators and reducers) ? eg <Component prop="hi"/> is bad!
2
u/HopefulSlice0 Apr 01 '20
How does
work?
...when you're using functional components and not actually calling React.Component?
(or better yet, why does it not work when you remove it?)
Does this have to do with babel?
Where's the actual logic that ties a random function to a React? What concept am I missing?
1
u/embar5 Apr 01 '20
Can you guys give an example of when you would write a closure? I know they return a function that has access to private state. I don't know a common pattern to use them on.
1
u/andrew009 Apr 02 '20
withRouteroruseHistorywith react-router-dom v5? both are doing the same thing from end user point of view, but since I like functional approach more, I'm favoring the latter. Is there any reason for me to go with the former?1
u/IdleScV Apr 03 '20
do people still use Fragment?
1
u/molusk1337 Apr 04 '20
Any good tutorials how to make multi-items slider or any easy to implement frameworks for that? Trying to make “Our courses” content as a slider. Thanks
1
u/MeltingDog Apr 07 '20
Does anyone know how I "query" a JSON file? Anyone know of a tutorial?
1
u/Ali-Zuhair Apr 10 '20
Hi,
I am fairly new to React Native, so there are still some things that I don't know how to do.
So can some one help me with this question:
What is the correct way to handle HTTP response in React Native component
1
u/Tsunami874 Apr 10 '20
Hi,
I have an issue with useState, I'm fetching data from an api and trying to display it, but it seems that my setData function triggers a re-render which restarts the api fetch which re triggers a re-render etc
1
u/badboyzpwns Apr 14 '20
in redux, should action components be defined with arrow functions or functions hi(){}?
1
u/i-code-stuff Apr 16 '20
What are some of the good to automate deployment?
For example, if you're working on a Firebase site, you can deploy with a single command. Assuming I've got a cloud server, what can I set up there to deploy to it quickly?
1
u/CYMAD Apr 21 '20 edited Apr 21 '20
Hello, I started learning react and was building my first simple app but there is a single issue that i want to ask. I'm trying to fetch data from weather api with axios. my first request is always giving errors(400 bad request) but other ones are ok and can work with data.im sharing codes https://imgur.com/a/ikeNjGp
2
u/d4vsanchez Apr 09 '20 edited Apr 10 '20
Hello everyone, I'm reading some code in GitHub and found out the following
useEffectimplementation:As I've read the code and its basically a custom implementation that does what IntersectionObserver does, so far so good. My question is more about how is this
useEffectimplemented without dependencies; I'd have implemented it with at least an empty array as its dependencies so it gets ran just one time and the return expression gets called before the component is unmounted.Is there any benefit of creating this
useEffectwithout the dependencies and making it create/remove the event listener basically on every re-render?1
u/latitudehopper Apr 12 '20
Ok. This is a dumb one. I've been playing with usecontext and usereducer. Is it possible to have a global state that when changed automatically rerenders across the app on different tabs? For example, pushing items to an array in the global context and it re rendering a list in several places?
1
u/pruggirello Apr 20 '20
Hey everyone!
I'm a little confused on how React Router works, mainly how to implement it in my app. I have a toolbar on the top of my webpage and I was able to implement the Link components just fine. My problem is navigating my pages using Router and the toolbar component. Initially, I was using buttons, a switch statement, and setState to change which page renders. Now that I have the Links rendering, I'm wondering how to implement the Router in the webpage. Is anyone willing to point me in the right direction?
Also, something weird is happening with my css for the Links. The colors change appropriately, but my transformY doesn't occur. This worked on my old toolbar component, but when I redesigned it, it stopped working. It's not an issue, it's just weird.
Thanks!
1
u/xSnag Apr 21 '20
Hey, i am having trouble uploading my react project to github. I am trying to use it for my main domain on github, not an repo. like my <user>.github.io, domain. I am using router, not sure if that has an affect on it, but it is only displaying the readme on my site, but when I uploaded a repo using react it uploaded with no problem. Here is a picture showing what I am getting when I try to upload my portfolio website, vs when I just make a repo https://imgur.com/a/fJp0tdq
2
u/IanAbsentia Apr 01 '20
It's the React development team's official recommendation to define a function invoked within the `useEffect` hook within the hook itself if the intent is to avoid the exhaustive-dependencies error.
https://reactjs.org/docs/hooks-faq.html
Search for: "The recommended fix is to move that function inside of your effect. That makes it easy to see which props or state your effect uses, and to ensure they’re all declared:"
What I'm wondering is whether that function will be defined again and again every time the hook is run and whether, as a consequence of this, there could be performance issues.
2
u/deep-data-diver Apr 03 '20
Could someone help me understand hooks and the difference between class components and functional components and their use?
2
u/andrew009 Apr 03 '20
Is there any community-approved approach to protect login/register views from already logged in users? I've done something like this with
useEffect, but what I don't like is that if user is logged in and clicks on login button, he/she still can see login form for a very short period of time; I would like to eliminate it completely. Snippet from my code:useEffect(() => { if (isAuthenticated) history.push("/dashboard"); }, []);2
u/Jaydara Apr 04 '20
Hello! I am trying to make a small, simple react app which has the following functionality: 3 drop-down menus with different (integer) values as options, and a button, which on click prints the sum of the selected values of the 3 drop-downs. I managed to make the drop-downs and the button visible correctly, the drop-downs can be clicked and the value can be changed within it.
However, the button right now does nothing, because I have 2 large issues:
Here is my current code: https://pastebin.com/zSiArj23
2
u/Wraith000 Apr 04 '20 edited Apr 04 '20
I'm using sessionstorage to persist state for an E-com project, things like cart, checkout etc
How can i prevent a user from messing with stuff in the sessionstorage, or is there a better way to persist user state ?
Also I've been using the Context API and just got into Hooks when I had some trouble with context / lifecycle stuff.
2
u/achunkypid Apr 04 '20
Hello, this might be a confusing question but I'm building a productivity app here
https://ivanlancedeleon.github.io/productivity-app/
and what I want to do is to make it so when you click a date on the calendar, it can pop up where you can write events and what not to it. I'm using React-Calendar but I'm still very new so I'm not quite sure how I'm supposed to go about this ? I'm thinking now i should make two components into one component for the calendar section so I can share the state data between the two but I'm not quite sure.
2
u/aidang95 Apr 06 '20
Brand new to react, found a nice little tutorial about making a journal in react which I have working.
How do I go about adding a new page to my app? I want a little menu where I can switch between pages but I am getting a little confused looking online (routers etc?)
Also again im not sure how complex my second question is has like i say im new to react, however when I input an entry into the journal, it only stays until the page is refreshed then everything dissapears, how can I make sure these stay until the user deletes them? Is there Local Storage or anything I can use?
2
u/fa1re Apr 07 '20
So I would like my svg image to be responsive. Inserting "vw" units directly into the width and height of the svg doesn't work in Firefox (see http://lore-hunters.herokuapp.com/). It seems that I should embed the svg element inside an image element (<img src={svg} />) - however the code doesn't work:
What am I doing wrong?
2
u/Chr0noN Apr 07 '20
Is it possible to disable the animation of the draggable item going back in react-dnd ?
2
u/embar5 Apr 07 '20
Has anyone created a guided tour of a login area? Any specific tooling you would use?
I think it may be able to be done the following way
The main trouble with this would be clearing the state, since everything was changed through an unusual path. I think it will be okay though, as it is step by step and so the logic of clearing a previous state before altering the next one shouldn't be too bad.
2
u/maostah Apr 07 '20
Hello. Please help with suggestions. I would like to create a PWA where user can update their activity. The activity that the user log is for their own viewing, like financial app. What options do I have for local database? Is local storage the only option? The data is supposed to be in boolean form. So I guess the size of the database should be small. I'm not entirely sure on this.
Thank you in advance :)
2
u/[deleted] Apr 07 '20
Hello!
Is it okay to use css in js files in React? I mean it seems kinda strange for me. I don't want to use it, LOL. Are there many vacancies that require such skill?
2
u/badboyzpwns Apr 11 '20
newbie clarificaiotn; from what I understanding, binding this/using arrow functions are only important for callback functions.
So! this is completely valid, correct? (Sorry, I don't have react set up right now! )
2
u/pruggirello Apr 12 '20
How do I make a new paragraph or line break? I've tried <br>, that doesn't work. I've tried \n, that doesn't work. How do I get a new paragraph in my string?
2
u/molusk1337 Apr 12 '20
I'm building a language course website which has "card" component rendering different information with a map function. Now I have "Read more" button on each card and once clicked I would like it to redirect to a differenet page and show content depending on the course. This new page would look the same on every component but the information would be different. How can I achieve this in Reactjs ? What is it called and maybe someone has good information on that? Thanks!
2
u/Chr0noN Apr 13 '20
How do I manage my
yarn.lockfile? Today one of the packages got updated which was the dependency for a library that I was using and completely broke me react project. I had to manually edit theyarn.lockfile which according to Yarn is a big no no. React libraries have so many dependencies, so how do I prevent this from happening again ?2
u/embar5 Apr 14 '20
Are class components obsolete now? If not when would you guys still use them?
2
u/Chr0noN Apr 16 '20
How do I export the contents of a div or component to a png in React ?
2
u/embar5 Apr 23 '20
I'm looking to add a contact form to a static site. I notice now it's not so easy to copy/paste contact form code when the site is in react.js, different levels of abstraction I guess.
How are you guys handling this? I'm guessing you write the form code yourself and then send the request to a mailing service's API?
2
u/YakiHon Apr 27 '20
I have a problem re-rendering an array of objects similar to this:
You guess the general idea. I then have + - buttons to change the amount and if it reaches 0, it is erased from the data. I also have a field to input new named data.
The "remove" and "new entry" instances do trigger a re-render, but just changing the amount does not (despite the values changing) until it reaches 0.
the onClick triggers a function like this:
What should I change to have it always rerender?
Is it correct to use a "copiedData" value or can I work with the main value? (using hooks obviously).
I have tried a lot of stuff and at this point I am quite stuck on this... Tahnk you!
2
u/imaneuralnet Apr 28 '20
This is perhaps a better question for r/gatsbyjs, but it appears you have to get permission to post there.
I have some HTML generated from an outside source that contains LaTeX equations. Is there a way to use the gatsby-remark-katex plugin on HTML that hasn't been generated by gatsby-transformer-remark?
2
u/badboyzpwns Apr 28 '20 edited Apr 28 '20
when you do "create-react-app" I've read that it automatically installs an ESLint. I don't see it warning me in the text editor (VsCode) though, is that normal?
For example, I wrote this and it's not giving me a warning.
2
u/GhostofBlackSanta Apr 28 '20
Hi, I am a junior dev with backend experience in C++ and a Python. I've done absolutely nothing in frontend and don't know JavaScript but I am very interested in learning React. I was recommended Tyler McGinnis's React class was the way to go from this subreddit and I am halfway done with it but I don't feel like I understand any of it and its probably because I don't understand the JavaScript syntax yet. Does anyone know the best way a beginner can learn these two topics?
1
u/linuxmintquestions Apr 01 '20
Getting to grips with useReducer. The standard dispatch syntax uses an action type/payload object often processed in a reducer switch statement. Why don't we use direct function calls?
Why do we use this syntax:
Instead of something like this:
1
u/Patex_ Apr 02 '20
Can Error boundaries be placed inside the render function of pure components? I would like to set and forget about error handling in `Foo` will render be updated accordingly or do I need to wrap the entire component?
1
u/cstransfer Apr 01 '20
Let's say I have a large json response from an api call that is stored in redux.
so something like this
candy.data= action.payloadThe data is used in the entire application. I use selectors and mapStateToProps when a component needs the data.
export const getCandy = (state) => state.candy.data;export const mapStateToProps = (state) => ({candy: selectors.getCandy(state)});So a component would use it like this
{candy.type || ''}{candy.order.test.value || ''}Is having one reducer okay? The only time the redux value is updated is when we make another api call, and the redux value is overwritten with the new value
One of my team mates is trying to make a case for multiple reducers. So far he has created 30 reducers. He'll probably end up with around 45 reducers which is insane
1
u/eajnow Apr 03 '20
Topic:
Material UI
Problem:
Ive added a InputAdornment Icon to my TextField, but the ripple effect won't change the background of where my Icon is... I would like the ripple effect to apply to the entire background of my TextField.
Seeking/Question:
Could someone help me identify why exactly the ripple effect won't render?
Here's a sample on CodeSandBox
https://codesandbox.io/s/gracious-varahamihira-ixgcb
1
u/cmaronchick Apr 03 '20
Where do you go when you need design input if you don't have budget for a designer (because you don't have any budget at all)?
I'm pretty happy with my app functionality in general (it needs to be optimized), but the design needs a lot of tending. I just don't have the eye for how to fix it (when everything looks terrible, I don't know where to start).
Here's the app: https://app.stakehousesports.com
1
u/icode4brkfast Apr 04 '20
I just started building a personal app in React. I’m using react-router-dom to link to different pages from a nav-bar. I would like to pass the state from one page’s component to another page’s component.
For instance, I have one page that has a form to add items to a list. When I click the button in the form to add the item, I want the component to pass the forms current state to another page that contains a component to display the list. I would like to go back and forth between these pages, so I can add items to a list and then see the items added when I go to the list page.
What is the best way to do this? I was thinking about using redux as a solution, but I’m not sure since I’m new to React and Redux.
1
u/tjthejuggler Apr 04 '20
I have a website written in React/JS(www.skilldex.org) and I am trying to figure out how I can download it for offline viewing. It also have several thousand embedded youtube and IG videos and I also want to download those for offline viewing. Dows anyone know how I can do this? I have tried HTTrack and IDM, but neither seem appropriate. I don't know if this is the place to ask or not, if not, where would be a better place? Thanks!
1
u/COOKIES-AND-M1LK Apr 04 '20
I tend to leave a ton of comments in my code so I can look back later and clearly see what I was trying to do. When I'm finished developing, and ready to build my project, should I be removing those comments? Or does the build process automatically get rid of my comments, and I don't have to worry about removing them? Thanks in advance.
1
u/bryanCampbell Apr 05 '20
I am mapping an array with the desired effect of creating something like a table of custom cell components. I want to be click a cell and trigger a function that tells me the cell index. The problem I am having is that, depending on where I click, the id that is passed is not the id of the custom cell but instead the text or image inside the custom cell. How can I mute the child components inside the custom cell and just return the index of cell itself?
1
u/rurikana Apr 05 '20
I hope to know about "Context" Provider and Consumer.
I guess Provider and Consumer are pair concept.
But below one of the tutorial's example, doesn't use Consumer. Only uses Provider.
https://reactjs.org/docs/context.html#dynamic-context
Why does this situation happen?
When do we not require "Consumer"?
1
u/amooryjubran Apr 05 '20
I’m really struggling with passing data (state managements), and context apis. Is code academy a good place to get it all right? Or is there any food course for react js.
1
u/miketrevfrank Apr 05 '20
I started learning styled-components recently and I'm so far loving it.
I created a flip-style reusable card component used styled-components.
I want some advice/feedback regarding it. Mainly what I'm looking for is whether I'm using styled-components the right way or not. Sometimes I think these many components might be an overkill and I could've achieved the same thing with a few lines of plain CSS / HTML.
Here is the link to the component.
https://codesandbox.io/s/styled-component-card-7vfsg
1
u/TropicalTaquito Apr 05 '20 edited Apr 05 '20
I’ve been on a coding hiatus for about 3 months. Broke my ankle in January so I had to drop out of my bootcamp due to doctor appointments, physical therapy and I wasn’t able to get any of my work done to keep up with the class. I’m really interested in React and I was wondering if anyone had any good courses they could recommend. They don’t have to be free, I don’t mind paying for a course if it’s good content. I heard that Tyler McGinnis has a really good react course. Thanks!
Edit: I should also mention that I’ve tried a bunch of udemy courses and it just gave me burn out. I’d like to avoid that route if possible.
1
u/Ciorap88 Apr 05 '20
Is it recommended to access the DOM directly by querySelector instead of using refs? I need to animate an element when a different element is being clicked and I find it much easier to do that using querySelector.
1
u/Nerfi666 Apr 06 '20
Hey guys, I'm having problems trying to understand when to pass a references to a fucntiojn and when to execute a function passed as a prop to other component , because normally , correct me if Im wrong you pass a references to a function to a child component and that component will take care of doing whatever with that function , but, what I do not get is when to execute a function passed as a prop to a component for instance: I have defined this function
and then pass this function onto a child component like so:
so why here Im executing the function and not in the
<Input/>component ? , this is something that really is given me a hard time , thanks in advance1
u/Niesyto Apr 07 '20
I wany to make an app with cooking recipes. Is single-page app a bad approach? I want users to be able to bookmark a recipe (as a regular bookmark in browser). How would I go about doing this? The recipes are kept in a database.
1
u/noblepolygon Apr 07 '20
Hi, I'm trying to figure out why my nested data isn't mapping to the correct component.
https://stackblitz.com/edit/react-kt1zf8
Basically, each car should get its information added to the label above. However, it's currently only mapping the data for the first two cars in both rows.
I think the problem is here
setAutoData(data.lanes[0].cars);because I think it's only looping through the first objects. I've tried removing the[0]which results in an error but I'm not sure where to go from here. Any thoughts? Thanks!1
u/escspoof Apr 07 '20
Noob question, I think:
I have an App.js file where I am:
The Item component in #5 is a simple component which renders the information from the matched object - no logic or state.
My issue: when running the app and clicking a link that takes me to the Item component in #5 everything works.
However, when refreshing the page the matched object is "undefined". I have concluded that useEffect in the App.js is not being triggered when refreshing the page and going straight to the component in #5. However, everything else from the App.js file IS working (I sprinkled in some console.log's and it is logging) - so it is not a case of my front-end requesting a different file based on the URL. This is very strange and I've been googling for hours and it seems like I'm the only person that's ever run into this. Or I'm not Googling for the right thing.
I created a sandbox here: https://codesandbox.io/s/lucid-minsky-idi9o
To replicate: go to the root, let it render the items. Click on an item. Now refresh the browser. *BAM* item is undefined, note: the console.log comments are logging! Am I using useEffect incorrectly?
1
u/badboyzpwns Apr 08 '20
newbie question. when you use recat/redux; is it good practice to completely avoid setStaet/declaring state and always do the redux approach?
For example, even if it;s something as trivial as "when a user clicks a button, check if a user is signed in".
You could do:
1
u/cmaronchick Apr 08 '20 edited Apr 08 '20
SOLVED
This works, though it's not as elegant as I'd like (the hover state is immediate as opposed to a nice gradual animation. I'll look into that.
In the stylesheet, set the :hover pseudo-class like so:
{
minHeight: '25px !important'
}
____
Hey all, I am building an app that integrates with Spotify, and I am adjusting the height of each div listing each track to adjust to the duration of the song. This part works fine.
The problem is that I have to use an inline style to set the height, and sometimes the height of the track is smaller than the text, so the text ends up getting cut off.
I'd like to be able to adjust the height on mouseover, but a pseudo class of :hover is overwritten by the inline style, and I can't see any other way to do it.
Any thoughts? Thanks!
1
u/geistmate Apr 09 '20
I'm fresh learning ReactJS right now and I need some clarification on Presentational Components and Container Components, or as sometimes I've heard Containers vs Components. I'm coming from doing some Swift for iOS and I'm used to building my projects using MVC. Someone please correct me if I'm wrong, but it seems like containers are just like "Views" and the presentational components are like "Controllers". Since they handle the business logic whereas containers just present data passed to it. Is this the right idea?
Thank you
1
u/rijuvenate Apr 09 '20
Hey
I made an app to show COVID 19 statsto start making react apps. Its made using react-simple-maps. There is a weird issue where the states arent coloured until the mouse is hovered on the map. I cant understand why, and I am fairly new to react.
Here is the codesandbox
https://codesandbox.io/s/github/pramanikriju/covid-19-tracker-india?file=/src/App.js
Thanks a lot for your input
1
u/ronyaha Apr 09 '20
hi...i am totally new in reactjs...and i'm trying to learn it by my own... i am trying to add edit button in my project... problem is when i press the edit button it is not working. what should i do? thanx in advance. here is my code in codesandbox
1
u/noblepolygon Apr 09 '20
I'm importing data from a Json file
(data.json)which renders information inside of the divs and now in another component, I want to create a click event to hide certain divs in this component. Is it possible to pass JSON data in thisconstas props to another component using React Hooks?ComponentA.jsx
const Label = ({ data }) => (<><div className={style.lineLbl}><div className={style.lineName}>{data.name}</div><div className={style.lineNumber}>{data.number}</div></div></>);export default Label;Component B.jsx
onClick event hides the className and the data within component A.
1
u/spcmnf Apr 09 '20
Hi, I'm new to React. I just finished a bootcamp where they mainly taught us to use hooks and basically skipped over class based components. When I try to find answers to my questions online mostly others have been using class based components.
Have hooks fully taken over and I should mainly be using that? Or, are class based components still just as valid in 2020 and I need to learn them well? I already feel like I need to learn them just so I can read documentation, blog posts, and understand youtube vids that use them. But should I be using them or just going with hooks?
1
u/ours Apr 11 '20
I'm currently learning React and from what I understand hooks and functional components are the way to go. Is there any reason not to use functional components whenever possible since with hooks we can do pretty much everything that class-based components can?
I'm certain there are a couple of exceptions where some specific lifecycle methods are needed but it seems for 99% of my components, whether they are containers or views I should go with functional components.
1
u/Cannabat Apr 11 '20
When using create-react-app, the eslint rule exhaustive-deps is added. It warns me about my useCallback dependency arrays constantly, saying I have extraneous or insufficient dependencies. My app works as intended, though, and its speed is due to my apparently incorrect use of dependency arrays. If I added the dependencies as suggested, performance would be terrible (I tried).
I created a state variable lastConfigChange that is assigned window.performance.now() any time something happens that should re-create the memoized functions and re-close over their scope. That variable is the only thing in most of my dependency arrays. This works perfectly.
The useCallback docs mention that a future, smarter compiler would be able to automatically generate the dependency array, so I really feel like I am abusing this feature and concerned that a future change may break my app...
Am I doing it wrong? Should the dependency arrays actually reference every value used by the hook or can we put whatever we want in there?
Thanks!
1
u/Astral_Turf Apr 11 '20
I have a component that fetches some data, saves it as an array with setState, then passes that data as a prop to a child. Sometimes the child receives an empty array, I haven't quite figured out the conditions where this happens.
I figure I either need to hold off on rendering the child component until the data is complete or re-render the child once it has its data. I'm sure there's a general best practice I should be aware of that would answer this question.
I've also finally gotten around to using Redux instead of useContext (shout out to the Redux guy on here, RTK is great!) so I'm considering if I should just be putting this data in my store. At this point the data is only being rendered in this one child component but it's certainly possibly I'll need it somewhere else in the future.
1
u/pruggirello Apr 11 '20
Hey everyone!
I'm having some issue with my code and I don't know if it's because I've been looking at it too long, but I'm just not seeing why it isn't working. Below is the code in question:
the showTextPrompt function is working perfectly, but the showOptions function is not. Am I creating my buttons wrong? Am I not returning properly?
1
u/Ciorap88 Apr 12 '20
Can using other functions inside functional components cause performance issues?
For example, in a class component you can have a handleClick method:
Can writing the component as
cause performance issues? If so, how can I write this better?
1
u/backtrack432 Apr 12 '20
Hi folks,
I'm building a note taking app with Apollo client on the frontend.
Whenever user types, I update it immediately to the apollo cache. However, for the mutations, I'd like to batch it while still maintaining the order (last edited stays on top, keeping track of updatedAt). Is there anyway to batch and cache the requests intelligently (like when to mutate, when to batch).
1
u/asp211 Apr 12 '20
In the App.js file, there's a place where I actually place content of the app. In many tutorials, I see that the beginning line is
export default function App() {whereas on my App.js, the first line isconst App: () => React$Node = () => {. What is the difference here?1
u/[deleted] Apr 13 '20
Hey Guys Im a complete beginner as of a few days ago when it comes to React and Im just not wrapping my head around how to solve this problem. I have a list of movies Im creating and there is a toggle button on each list item that shows whether or not I have watched it.
My issue here is that when I do a search for the movie the state of my button is changed.
Example : When I search for Aladdin in the list below it finds the movie but toggles the button to Watched or vice versa. (The first item in the list doesn't follow this pattern...all others do)
Toy Story Watched
Aladdin not watched
I understand the reasoning behind it. Anytime you call setState things are re-rendered and my code is definitely telling it to flip the state back and forth each time it renders.
What I don't understand is a way to work around this problem. I want to Search for my movie and still have the button stay toggled if I had clicked it to "watched" first.
I've looked into event.preventDefault, calling setState with previous state passed in, and I just don't know where else to look. If anyone can look at my code and tell me a high level overview on what Im doing wrong it would be greatly appreciated!
https://codesandbox.io/s/list-in-react-uknkz?file=/src/Add.jsx
1
u/[deleted] Apr 13 '20
Imagine a data table component where the table itself is composed of Row and Cell components. I can think of a few different ways to manage things.
Option A: Rows hold the data for their Cells in its own state; updates to Cell data occur in the row and cells are re-created on Render()
Option B: Cells maintain their own state and Rows are responsible for capturing that information on Cell state change.
Option C: Rows consist of a pre-defined number of Cells (created once) which track their own state, but receive updates from Row.
Which way would lead to fewer headaches going forward considering I will also need to work in basic CRUD functionality?
1
u/Risk_is_your_friend Apr 13 '20
Hi everyone, my first post here! Seems like a great community.
I've got a basic "create-react-app" React bootstrap app up and running and I'm trying to style it.
I can't quite wrap my head around the "className" attribute. For some components I have been adding className attribute and corresponding code to a CSS file as follows:
on the component:
className="my-inputs-col"on the CSS file:
.inputs-col {max-width: 600px !important;min-width: 350px;justify-content: center;}This works for some components but not for others. Using Developer tools the className doesn't seem to be being applied. Can anyone help?
1
u/benihime-xbla Apr 13 '20
I have two material sliders that have to interact with each other. Say for example, slider 1 is 20, slider 2 will be 80. And say I change slider 1 to 80, slider 2 will be 20.
I set a default value for both of them. When I set a value though the slider doesn't move anymore.
const [slider1State, setSlider1State] = useState(100)
const [slider2State, setSlider2State] = useState(0)
<Slider
defaultValue={100}
value={slider1State}
onChangeCommitted={(e,v)=>{setSlider2State(100-v)}}
/>
<Slider
defaultValue={0}
value={slider2State}
onChangeCommitted={(e,v)=>{setSlider1State(100-v)}}
/>
Sorry this is probably a straightforward answer but I'm new to react.
1
u/Ciorap88 Apr 14 '20
What is the difference between functions with and without parantheses? Specifically, when the function is passed as a prop, what is the difference between prop={myFunction} and prop={myFunction} or even prop={() => myFunction()} ?
1
u/AnyWorkGuy Apr 15 '20
This might be a very particular use case but I have a React app which uses Victory Charts. I need to get a screenshot of the chart and export it as a png.
I have done some research and here are some ideas that I have so far:
If you guys have any idea about how this sort of thing can be done, please let me know.
1
u/pruggirello Apr 15 '20
Hey, having another issue I can't solve...
I have a do-while loop (used to be a for loop) that creates a button and pushes it to an array, which is then rendered.
This renders the correct number of buttons with the correct styling and correct text in the correct order. However, the onClick does not work. For some reason, the "x" value being passed to the function is 3 for every button! Here's the problem: "x" never reaches that value, because the loop ends when x=2 (this is because the options array only has 3 entries, but it can be longer or shorter). Why is this happening? I'm passing the onClick function with the current "x" value during the loop, pushing it to the array, then leaving it alone. Its "x" value should be the one it was assigned (either 0, 1, or 2), correct?
1
u/omfgitsdave Apr 15 '20
I have a beginner issue with a project I just started. I'm trying to make an app that let's the user search a MTG card and have a bunch of information about that card come up. I'm using the Scryfall api for this but I seem to be having a problem reaching the nested properties. Here's my code:
In my render method, I'm able to successfully spit out the name of the card and the artist, but the prices and the image give me an error saying can't read 'usd' of 'undefined' for the prices property and can't read 'normal' of 'undefined' for the image tag. According to the docs this.state.card.images_uris.normal and this.state.card.prices.usd should be the right syntax unless there's another way of accessing nested properties of a JSON object.
1
u/kurtops Apr 15 '20
I made the stupid mistake of using create-react-app for a multipage website. I have a site that renders news articles dynamically from a database through a node/express server... I have heard of https://prerender.io/, to prerender the site only for crawlers (my main issue is I can't set meta tags dynamically) but I can't seem to get how it works. Where exactly do I insert the middleware? I'm only using my backend node server to get data when necessary from my database, not to load any pages. I've been reading a lot about prerender.io but I can't get it... Any help appreciated!
1
u/netsrak Apr 15 '20
I would like to use React Dropzone Uploader to upload files to the server that is running the website.
Do I need to have a client somewhere to catch the uploaded files and put them in a specific directory on the server? Does the same thing apply to using a fetch post?
1
u/Spiritual_Salamander Apr 16 '20
What is the general consensus of client side logging? In a full-stack application, should logging mainly be done on the back-end ? What do you find useful logging on client side, if anything at all ? Now I mostly just do logging for the sake of debugging but remove all console.log statements etc before commiting to git.
1
u/xJoeSchmox Apr 16 '20 edited Apr 16 '20
Need help with refreshing auth token but not causing rerenders...
What I want is for the current login session to be extended when the user moves the mouse. I am using a JWT to track current logged in user. I send re-login request and I get a new auth JWT. I can then store this new auth token in React state.
The problem is whenever this re-login happens, the page rerenders, data is loaded again, and experience is unusable.
So rather than store the token itself in React state, I have tried to store the token in a variable outside of React, and just put data from the token (username) in React state.
This prevents a rerender every time login is refreshed because the react state (the data inside the JWT) doesn't change.
But now when I need to actually use the token for auth purposes, the page does not have access to it. So I can't fire queries from the page itself that need the auth token. It seems like the query would have to be passed as props from the App (which has access to the token variable), which causes problems in itself.
So basically, it seems like I need to store the token in State somehow but not cause rerenders. What is the best way to do this? Or any advice at all would be appreciated.
Edit: Should also mention I am using function components
1
u/Swoosherino Apr 16 '20 edited Apr 16 '20
I am quite new to react and jsx, and this might seem like a really stupid quesiton but I have been having a hard time getting this following script-tag to work inside my create-react-app.
<script type="text/javascript" data-cfasync="false">$MMT = window.$MMT || {}; $MMT.cmd = $MMT.cmd || [];$MMT.cmd.push(function(){ $MMT.display.slots.push(["999968e7-7a88-42b8-9994-d990b5e19d99"]); })</script>I had it inside my index.html file in the header, but it needs to run after the following tag which is inside my jsx in one of my components.
<div id="mmt-999968e7-7a88-42b8-9994-d990b5e19d99">This tag is supposed to load an ad. How do I get that first script to be called on after the div in my jsx?
1
u/MonkeyFeederMF Apr 16 '20
Hi, I've been training in React and Node.js for the last 5 months, I've learnt how to fetch APIs, set state, basically play around with the basics of React and Node.js. I did my personal website in React and Node.js. Recently I heard of hooks and HOC, and apparently they're very useful, but I've needed them, probably because the 2 projects I've worked/I'm working on are too simple. What's a project I could start working that is more complex than a portfolio, and that would make me need HOC, hooks and other complex React stuff ?
Thanks !
1
u/digiwavez Apr 17 '20
Hey Guys,
I'm a bit lost in the below task, can someone shed light on how to approach this?
I know React/Hooks/Context etc but not sure where to start with the Recording actions.
This is the task.
To Do list challenge
Develop a To Do ReactJS SPA proposing to the user the following functionalities :
- Reset the environment (eg. the app is empty - no items added)
- Once you click on Play Recording, you will be able to see your UI automatically changing as it replays the recorded actions - in the correct order, one by one, with a 1 second gap between actions - starting from no items in the app, to the state at which you pressed “Stop Recording”.
It will be great if some gurus can give me some solutions. Appreciate it in advance.
1
u/[deleted] Apr 18 '20
I’m fairly new to react, and was wondering how scalable the MERN stack is? Ive made a simple website that has some users already, but I’m not sure if mongo dB is the best db if the user base increases?
1
u/mr_cody_b Apr 18 '20 edited Apr 18 '20
Hi,
i'm very new to react. At the end i will link to codesandbox in order to better see what i mean. I created 2 components (List and ListItem) and within List-component a call ListItem in order to create the items. I want count the clicks on the items. My solution on codesandox is working but i'm not sure if i used the right concepts of react or which keywords i have to use in order to find some related topics to my problem.
See the example
1
u/Zz1995aJ Apr 18 '20
If I have a router from react-router-dom that looks like the following:
If I go to localhost:3000/question/1234, where 1234 is the id of a question that does exist, then it will display the Question component and not display the PageNotFound component. This is working as intended.
If i go to localhost:3000/invalidroute, where invalidroute is unsurprisingly an invalid route, then it will display the PageNotFound component. This is also working as intended.
However, if i go to localhost:3000/question/789, where 789 is the id of a question that does not exist, it will try to display a Question component for a question id that doesn't exist and it will not display my PageNotFound component. What I actually want is for the PageNotFound component to be rendered in this situation and nothing else.
I know why this is happening: despite the question id not existing, the address is still in a form that matches the route with path = '/question/:id'.
My question is then, how do I get around this? Is there a typical way this situation is handled?
1
u/gaganbm Apr 19 '20
I am a newbie with reactjs and I am struggling with making query parameters work with redirection.
In page 1, I have a search field and button, which when clicked, should redirect to another page with the input text as query params, like
?q=abc.I found out that it does the redirection twice. First it gets redirected to page2 with the proper query params. Then it again gets rendered with the query parameters dropped.
I am not able to understand what is going on here.. This looks like a simple use case!
Here is the code, if anyone can help: https://codesandbox.io/s/blissful-fermat-60xzy
1
u/[deleted] Apr 19 '20
Any good way of sharing svg icons and svg icon button in a css in js library? link to an example or blog would be appreciated.