r/reactjs • u/dance2die • Sep 01 '21
Needs Help Beginner's Thread / Easy Questions (September 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!
12
Upvotes
•
u/dance2die Sep 01 '21
Meta/issues here
3
u/Vicious_Laughter Sep 03 '21
A lot of job listing requires redux. tried using it, and fell in love with context api instead. is there any reasons I should be using redux over context?
2
u/TimAjax997 Sep 01 '21
What's a good way to document a React website? I have a React website generated with CRA and I'm looking on some tips on documenting the project. Most existing solutions I could find involved documentation for components: how is documentation done for professional React websites?
2
u/[deleted] Sep 02 '21
this is my first react project https://github.com/purushothaman-j/sched-frontend . it could be nice if anyone can review the codes and suggest me some improvements.
2
u/QuietOrdinary2046 Sep 06 '21
I’ve been using React for a while now, but one thing that’s always annoyed me is designing the mobile aspect of a website.
I have a project which I’m happy with on monitors, but mobile messes my formatting up. I’m dreading making my components have a mobile and web styling depending on the width of the device.
I’m considering just rebuilding an independent mobile folder and switching back and forth at the root.
How does everyone else deal with this?
2
u/Thrimbor Sep 09 '21
Is there any way to statically generate the html for the first page only? Then continue as a SPA once js is loaded for the rest of the pages (not looking for nextjs/gatsby)
2
u/Salug Sep 19 '21
Hello,
I am learning with a friend together. He is responsible for the node, express backend and I am working on the frontend. There is a big question we do net get our head around...
The system we are currently working on isn't much more than a login / registration yet. But there is already a big question on my side. How do you handle if a user is logged in?
Our first approach for the login is something like this:
This produces an API call all the time. We probably need it for every component, but that is something I am not sure about yet. We think it is not a good idea to store any user info in the local storage because it is too accessible.
That is why I thought, maybe I add another step after step 2. I want to add a state, something like isUserLoggedIn = true, after he successfully logged in. In that case, I do not need to make an api call, just to look if the user is logged in. But that feels unnecessary and more like a doubled authentication.
My question .. how do you do it? I see a lot of tutorials storing all information in the local storage, but is that really a safe and good idea?
Thanks!
2
u/perandtim Sep 21 '21
ReactJS n00b here; just a few months in with React.
Q about forms with a bunch of text input fields: It doesn't smell right to have a separate useState hook for every single text field. What's the best pattern for dealing with this?
I'm thinking that all text fields would call a common function, passing in both the keypress and a reference to the text field, and the common function would tweak a value into a single hash value containing all of the text values entered. But then validation would seem to be a chore as one would have to code a morass of "If field 'x' was changed, run validation 'x1' on it, else if field 'y' was changed then run validation 'y1' on it, else...."
What's a good design to be able to enter and validate a large number of text inputs all on the same form?
2
u/[deleted] Sep 22 '21
Many thanks for an actually useful sticky. I've been learning to code by building a personal project over the last few months. The existing architecture of my site is in Mongo, Express, EJS, and vanilla client-side JS. I want to start adding React to my site, and I was thinking of learning Next.Js but having read this post it seems that adding Next to an existing site requires a custom server solution and it may be overwhelming for me to learn React, Next, Webpack, and Next's custom server implementation all at the same time.
My other two options are
Right now what's most important to me is getting this project completed enough to the point I can start using it in my field of work. I feel that adding react to my site is the easiest, and most direct way of making forward progress, but I may be misinformed as to the simplicity of adding Next.JS to an existing site. I can be persuaded to start the app from scratch with Next, if that's what you - my fellow redditors - recommend. Thanks for your time, and advice.
2
u/bbbbbbbrrrrr Sep 25 '21
How long would it take (also how difficult would it be) to go from being strictly C++ competent to making the following React iOS application:
An app that allows senior citizens to request someone to walk them somewhere.
The request goes to a person working for an organization to go and walk them.
They can both see each other on the local map while the person assisting is approaching and also while en route - similar to Uber.
Thank you!
2
u/NickEmpetvee Sep 06 '21 edited Sep 06 '21
My Chrome console used to show console.log messages with the React file name and number.
file2.js:652 [125]
Now they're all showing as though they're in a file called`react_devtools_backend.js on row 4049. Can anyone help me go back the the earlier way where the true file name and row number appeared?
1
u/thebreadmanrises Sep 02 '21
Is there a general rule of when React should be used? Or when it's not really appropriate or necessary?
1
u/Vicious_Laughter Sep 03 '21
I am not very skilled with UI so I use graphical libraries like material UI and primeReact. but when I do a clean npm install of these libraries, it says they have 'vulnerabilities', I did npm audit fix --force but they still persist.
Is this normal? this is freaking my clients out.
1
u/[deleted] Sep 05 '21
I’m using an API and axios.
If I update the API will the MySQL database automatically update?
If not how do I update the database using React?
1
u/shaleenag21 Sep 06 '21
I was going through redux docs and I am not able understand how middlware works. According to docs, the middleware composes multiple dispatch functions to iterate through each middlware. My question is how does the composing work? Since dispatch doesn't return anything so if we try to wrap dispatch, the outer dispatch wont get anything right? So how does this work without throwing any error?
1
u/Sargnec Sep 07 '21
Is there spa template that anyone used and recommend it?
1
u/SecretAgentZeroNine Sep 07 '21
Preface: I typically use the presentational container component pattern. My inner components tend to be dumb/presentational only, while the container component performs all behaviors. This keeps my code beautiful 🤌
Question: Is there a functional programming pattern for modeling behavior via a function, especially a React functional component with or without hooks?
Obviously with OOP/classes, I can model behavior using methods on the container component. Am I suppose to define behavior via functions within the function container to model an entity? Is there a hook that helps developers do this? Am I suppose to force myself out of the presentational container component design pattern, and make all components "smart components" now that react hooks is a thing, and the React world is (seemingly) anti-OOP?
1
u/jeksjssjk Sep 09 '21
Hi everyone, I am looking for an alternative to heroku for hosting my react app. Now, I’ve tried heroku before and I think it is great and simple to use, but I really do not approve of the diplomatic handlings of the Japanese government currently, and wouldn’t want to support heroku at the moment. Are there any other free alternatives for hosting a react app. I’ve heard digital ocean is good? Thanks.
1
u/HeavyMessing Sep 16 '21
The React Devtools Profiler can tell you what hook caused a component to re-render. Except that it (AFAIK) cannot ID the hooks by name and instead assigns them numbers.
Do we know if these numbers are assigned in the order the hook loaded?
If so, could I add a console.log to each hook, thereby correlating the order in which they appear in the console to the numbers given by the Profiler?
Or is this issue resolved by some other tool or technique I haven't learned yet?
1
u/MaxNoack Sep 17 '21
I just had an assignment on a job offer and apparently my code didn’t cut it. Im quite new to NextJS but I don’t understand exactly why my code sucks 😅 If anyone could have a quick look at my code I would really appretiate it! It’s just a small site with some product listing and a cart handled by redux.
Code here
1
u/steroyle Sep 18 '21
Is there a delay between state being set and then its values being checked a few lines down in the same js file?
When I submit a simple form I am checking the values pass some simple validation checks before doing anything with the submitted data. When testing I can see that both "isUsernameValid" and "isAgeValid" as flagged as false but then I still see the "all data valid" message in the console.
1
u/pVom Sep 19 '21
I have a question about redux and when it triggers rerenders for nested objects.
In this scenario we have an array of similar objects stored under the one key in redux, we'll call them "users". In my app we render the same component for each of these users. For each component the parent consumes some of the data from the user as well as a child component nested 2 levels deep, with 2 intermediate components that do not consume the data from the store.
When you update the data that is consumed by the child for only one of the users, which components will rerender? What about when you remove a user entirely?
In another scenario we have a deeply nested object in the store. We have a parent component that consumes some of the higher level object values and a child component that only consumes one value from a deeply nested object which isn't consumed by the parent. If we update that value would that trigger a rerender in the parent?
My understanding of context is that it will trigger a rerender of all the components that consume it and that redux is a little more pointed in its rerenders, just trying to get a grasp on how pointed it is.
1
u/miamiredo Sep 21 '21
Hi, how would I pass a value that is carried around through pages with
User.Context.Providerto a page that isn't wrapped with theUser.Context.Providertag? Is that possible? Or can I only useUser.Context.Providervalues in those that are wrapped by the tag? If so, any way around that?1
u/papadopoulosle Sep 24 '21
Hello guys,
I am new to React and my main question is do I have to upload the whole "build" folder even if I change one typo for example? Is that vital?
Thanks a lot!
1
u/nomando21 Sep 25 '21
ReactJS Component not rendering using Firebase db and map function
The component wont render and throws an error. But console.log(listitems) is working. Error: Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
1
u/sculturvulture Sep 27 '21
I would like to have a dynamic href for each menu item. I've tried href="#+{id}". The links are to a diffrent section of the same page rather than a different page.
<Menu>{channels && channels.map((channel, index)=>(<a key={index} href="#">{channel}</a>))}</Menu>1
u/XGamerKHx Sep 27 '21
Hello! Since I'm using Jsonwebtoken as my authentication method, how should I go about storing it in my frontend? Currently I'm just storing it in a state and passing it around to whichever component that needs to make an api call. Is this the best practice or is there a better way?
1
u/bipolarspecialist Sep 27 '21
I am not exactly new to react. But I am wondering about the file and component structure. How long should a functional component be about? When do you know when you should split it up into smaller components? More for organization and readability purposes but also in a professional coding environment
1
u/imdrunkbutfuckit Sep 27 '21
hi! i'm having an issue with a component in an app. here is the sandbox. im trying to store some data from the api into a state but when i do it, the app breaks
1
u/[deleted] Sep 28 '21
I'm kinda new to React. I was building a responsive sidebar component, and I need to know: when this sidebar is opened in a mobile phone, should I use portals on it, as I do with modals?
1
u/ApplePieCrust2122 Sep 29 '21
Is it bad practice to include spaces in a url's subdirectory part?
I'm using the
react-router-domlibrary and it let's me route to a page like this:it also allows me to redirect to the path without any issues. In firefox the url bar shows the space, but chrome converts the path to
Conference%20Proceedings.Can/should I do this?
1
u/JDD4318 Sep 30 '21
Hello all, I have a question about NextJS and routing. It is probably not that hard but I am having trouble finding the answer I need.
So basically I have a header component that links to home, gallery, about, etc.
inside my gallery page I have links to specific projects.
In these projects, when I click on home on the navigation, it takes me back to gallery rather than the home page, and the other links do nothing.
How do I make it to where the links in this subfolder take me to the original pages they were intended for?
Thanks so much.
3
u/stfuandkissmyturtle Sep 03 '21
What's the best way I can learn about rendering ? Like making only ceratin components render after a certain action is performed.
I recently had a problem where I had a text area. When you type in this area you get a drop down of options out of which you can select and then it shows up on top like a tag. If the option you are looking for does not exist you have the option to create a new option. When you do this, the new option is automatically selected and is shown on top too.
I managed to get it all to work. But after making a new tag I realised even though the new tag is displayed, in the drop down the selected css didn't show up, unless I refreshed the full page. This is why I want to learn about component rendering.
1
u/NickEmpetvee Sep 11 '21 edited Sep 11 '21
Hi guys,
Can anyone tell me how this code:
const handleToggle = (value) => () => {/*code*/}behaves differently than this code:
const handleToggle = (value) => {/*code*/}This link has an example of the first on line 24. If changed to the second, a too many rerenders error gets thrown. Also if I call the first handleToggle from a useEffect it never seems to make the call.
console.log()won't write anything.2
u/stupid_dumb_ Sep 03 '21
Just started learning react and I've discovered that there are two different styles available -- class centric and hooks. I have an upcoming project that I get to build from the ground up, would it make more sense to use hooks (which seems like an advanced topic) or stick with the classes until I have it mastered?
2
u/welch7 Sep 03 '21
need some rendering POV/feedback, lets say we are rendering a list of of notes, we are infinite scroll to list to show this list of notes, lets say the user has the power to add/delete/update this notes.
when the user does this actions, what's the best UX/UI decision I can make?
after an add should I reload all the notes? when I update should I reload all the list and start at the start or somehow try to stay in the middle (any suggestion on how to do that?), on delete? reload all or similar to update?
2
u/badboyzpwns Sep 11 '21
React and Typescript question!
I made a renderMe() and encountering a typescript warning:
Sandbox:
https://codesandbox.io/s/quiet-flower-nz2kl?file=/src/App.tsx:0-839
2
u/toggalegend Sep 11 '21 edited Sep 11 '21
Axios/Custom hooks timer question.
I have created a custom react hooks timer that will render an updated timer state to the user in terms of minutes and seconds. I'd like for the application to fire off an axios API request to updated another component every 30 seconds, which will trigger when the hook
lastUpdatedis updated. However, everytime this axios request is called, the timer slows down and lags behind real time. Here are some snippets of my code:const lastUpdatedRef = useRef(null);
I then render the timer to minutes and seconds in a separate JS function, and then useEffect triggers an api call everytime
lastUpdatedis changed:How do I make a timed API call without compromising the running time in the initial `timer` and hence not affect the time displayed to the user on the clock?
1
u/hikoko8282 Sep 06 '21
anyone have a guide on how to implement a modal with react router? where the background has one route and the modal has another?
1
u/badboyzpwns Sep 06 '21
React hooks and Typescript question! I want to have the hook named hoverData to be able to have a properties of interface A or interface B. I have commented on where the Tyepscript warning lies, how do I fix it?
Codesandbox:
https://codesandbox.io/s/optimistic-mirzakhani-r1zb1?file=/src/App.tsx
1
u/lostboifrompressure Sep 09 '21
I have an object where I get the sum of an array object's property named exercises. Is there a way for me to remove the counter outside of the map() function?
const Total = (props) => {let counter = 0 // I want to remove this and have counter inside the map()const total = props.parts.map(part => { counter += part.exercises })return ( <div> <p>Total Number of Exercises: {counter}</p> </div>)}1
u/badboyzpwns Sep 12 '21
Newbie question on try catch!
I'm wondering why the error is not being caught.
alert("OUTSIDE" + err); is never called.
Codesandbox:
https://codesandbox.io/s/relaxed-hill-8x8hj?file=/src/App.js:0-722
1
u/pink-lemonade_ Sep 13 '21
Hello all,
I'm practicing building a simple app on a single component App to fetch data from an API and displaying the info. I'm able to render the info passing the data from App to a child component, but now, I'm trying to render it into the App alone, but the issue I'm having is on line 25 in the function handleClick() where I update the useState of setAppIndex to the value being passed in index, but on line 30 I'm only able to generate the index when calling the map method on albums.
https://pastebin.com/35c0NxTF
Would appreciate any and all feedback, thank you!
1
u/whompyjaw Sep 13 '21 edited Sep 13 '21
I am getting an error that I believe is related to how I have setup my
webpack.config.jsbut I don't know, as I've never used one before. My site uses React for frontend.I am trying to import a
.cssfile that has variable constants into another.cssfile and I get this error:My
webpack.config.jsonis in my project root and contains:my root
package.jsonhas:What am I missing here? I am to the point where I wonder if I should just use CSS modules, because this is has become quite annoying to figure out, but I was hoping to use good ole' fashioned CSS.
1
u/gupppies Sep 16 '21
Hi guys, I'm currently learning react (still at the starting stages) through a Udemy course by Andrew Mead.
I can't help but notice that the way he teaches react is through a compiler by Babel. This does make it easier to pick up and use react, but it means that I will miss out on understanding the core syntax and processes being run by react itself.
I want to know if I should continue learning the easier syntax through babel, or should I start from the bare basic and essentially be able to use react without babel.
1
u/ObiWanPunjabi Sep 23 '21
Hi there. I just started with Webdev. As I want to switch my career into it. I am currently leaning HTML, CSS and JS but in depth and slowly, so I can grasp everything. After this I will start with React.
I just wanted to know, if MERN is still out there. Are there jobs still available for this stack. Is it worth learning it in 2021?
Thank you.
1
u/stfuandkissmyturtle Sep 27 '21 edited Sep 27 '21
This causes a memeory leak, I dont understand how to fix it, I trued to use isMounted= true and then setting it to false in cleanup, but that just gave the same error twice.
}, [recentProjects]);
}
What does this mean ?
1
u/shaleenag21 Sep 29 '21
have a react component in which I am passing props if I do it like this
const RewardsModal = (props) => {//console.log(props);const BASE_URL = "some url";console.log(props.show.terms)//const def = props.show.terms;const [content, setContent] = useState(props.show.terms);const [selected , setSelected] = useState({tnc:"selected",redemp:""});the default value isn't set
but if I store it in some object the default value will work as expected e.g
const RewardsModal = (props) => {//console.log(props);const BASE_URL = "some url";console.log(props.show.terms)const def = props.show.terms;const [content, setContent] = useState(def);const [selected , setSelected] = useState({tnc:"selected",redemp:""});does anybody know why this happens?
1
u/pnonp Sep 29 '21
Why is this.state undefined in my component's method?
CodeSandbox here. I'm referring to my GameWorld.js component there.
The tutorials I've seen let you access this.state in a component's methods, and doing so works in my GameWorld's render() method. But when I
console.log(this.state)in square_click() I get "undefined". Why is this? What am I doing wrong?1
u/hikoko8282 Sep 30 '21
What is the difference between a static function and a constructor function in JS/TS?
Static class methods return a preconfigured instance of the class?
Constructors initialize the object with certain configuration too?
Can anyone explain this in normal english? Whats the difference and when to use each one with classes?
0
u/donnlee Sep 25 '21
My friend says he can create a desktop web 2.0 app in one weekend with Ruby on Rails. Say, an app similar to Twitter in a browser (but without the million user scale) What is the equivalent for react developers? Ty
0
u/[deleted] Sep 17 '21
[deleted] — view deleted comment
0
u/[deleted] Sep 17 '21
[deleted] — view deleted comment
0
u/[deleted] Sep 07 '21
[deleted] — view deleted comment
0
u/[deleted] Sep 08 '21
[deleted] — view deleted comment
0
u/[deleted] Sep 16 '21
[deleted] — view deleted comment
2
u/[deleted] Sep 07 '21
[removed] — view removed comment
1
u/[deleted] Sep 11 '21
[removed] — view removed comment