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/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/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/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/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/[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/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/GulyFoyle Apr 19 '20
Should i pursue learning best practices or master what i find reasonable and easier to understand for me ?
I've been trying to learn react for few months now , i started by class based components , lifecyclehooks and context api and now these are "older" methods replaced by funcional components, hooks etc.
It feels like im always starting over trying to find best practice in a rapidly changing enviroment and since i am not doing this professionally i have no idea what real world problems require.
Would appreciate any kind of advice on this matter, thank you.
1
u/ShitHitTheFannn Apr 21 '20
I'm building a Gomoku game in React (it's like Tic-Tac-Toe but on much larger board). I use a multidimensional array to represent the game state. But since react does not permit mutability, I have to use Array.map() to mutate the game state which has O(n) time, which for a simple operation like this should be constant. Is there anyway I can mutate a specific cell in my array in constant time?
1
u/Astral_Turf Apr 22 '20
Can someone post a definitive guide to conditional rendering? Something relatively advanced would be great. I clearly don't have a good handle on it because I can only get it to work by tweaking things haphazardly and then things tend to break in unexpected ways.
1
u/csvtom Apr 22 '20
Could you tell me please a real world examples about high order components; that kind of cases when you say "Yes, here is a good solution" Thank you <3
1
u/backtrack432 Apr 22 '20
Is there a way to programatically focus on input/textarea/texteditor when hitting a specific key like enter?
1
u/Vtempero Apr 23 '20 edited Apr 23 '20
I am willing to use Gatsby for a small pet project. Can you please help me understand some points:
thanks in advance.
edit: this page has all the answers: https://www.gatsbyjs.org/docs/porting-from-create-react-app-to-gatsby/
1
u/GhostofBlackSanta Apr 25 '20
Hi I'm new to React and JavaScript coming from a C++/Java background. I'm taking a course on React but my biggest problem is understand what part of the code is React and what part is JavaScript. Is there an easy way to distinguish the two?
1
u/badboyzpwns Apr 28 '20
Goal
I'm creating a sign in or sign out button with Google's authentication. If a user is signed in. a sign out button would appear. If a user is signed out, a sign-in button would appear.
Problem
I always thought React hooks would essentially replace classes 99% of the time
But I think this code is not suitable for hooks because I only want to setup google's OAuth once at componentDidMount(). Using a hook will make me set it up multiple times, making it redundant.
Please let me know if I can transform it into hooks.
With classes:
With hooks:
1
u/geo_n1ght Apr 28 '20
Hello. Quick question.
I want to connect a React UI to a backend that gets data from another system. The UI will only read data from the backend but I want it to query the backend somehow and auto update without clicking any button (auto update ?). Where shoulf I look because I have no idea where to start?
1
u/Jorick_DC Apr 29 '20 edited Apr 29 '20
Quick question
I am trying to build following functionality. on your screen you have two buttons A and B. When you press button A, form A should appear instead of the buttons. And when you press button B, form B should appear. How do I best do this?
I was thinking along the way of conditional rendering.
1
u/badboyzpwns Apr 30 '20 edited Apr 30 '20
1.is it a good idea to always use anonymous functions for helper functions? I just wanna avoid the "this" bind error sometimes.
2. Aside from the benefit of manipulating this.setState(); are classes just syntatic sugar for functional components? Does it matter if I use classes for everything (let's ignore the fact where react hooks can be more efficient in some cases). Will it slow down performance?
1
u/sssmmt Apr 30 '20
I've come across this compound component that's configured using special children components. It looks like this:
What's the name of this pattern? How does parent Grid change its behavior depending on its children?
0
u/[deleted] Apr 14 '20
[deleted] — view deleted comment
0
u/[deleted] Apr 20 '20
[deleted] — view deleted comment
0
u/[deleted] Apr 30 '20
[deleted] — view deleted comment
0
u/[deleted] Apr 29 '20
[deleted] — view deleted comment
0
u/[deleted] Apr 04 '20
[deleted] — view deleted comment
2
u/[deleted] Apr 20 '20
[removed] — view removed comment
1
u/[deleted] Apr 08 '20
[removed] — view removed comment
0
u/[deleted] Apr 19 '20
[deleted] — view deleted comment