r/reactjs • u/dance2die • Mar 01 '22
Needs Help Beginner's Thread / Easy Questions (March 2022)
You can find previous Beginner's Threads in the wiki.
Ask about React or anything else in its ecosystem :)
Stuck making progress on your app, need a feedback?
Still Ask away! We’re a friendly bunch 🙂
Help us to help you better
Improve your chances of reply
- Add a minimal example with JSFiddle, CodeSandbox, or Stackblitz links
- Describe what you want it to do (is it an XY problem?)
- and 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 still a growing community and helping each other only strengthens it!
19
Upvotes
3
u/Tixarer Mar 12 '22
I want to implement infinite scroll to my app and I'm using 'react-infinite-scroll-component' package. The problem is that I don't know what function I need to give to the next inside the InfiniteScroll tag and how to make the hasMore false when there is no next page ?
Here's the CodeSandbox
2
u/Younes1255 Mar 03 '22
My First Experience
Sooo , i had my first internship and i feel a little bit nervous about the task that i'm designed to do . i'm not fimiliar with react so what are the best advices to follow Guys
Application : application allowing its user to do a trading simulation on the stock market : sale and purchase of shares.
Technologies :
- React ( Carolina Dashboard )
- PostegresSQL
i'm assigned to do the managing of the wallet :
- Decision-making tools using PER ( Price to Earnings Ratio )
- Graphical analysis using ( bollinger bands , fibonacci retracements , eliott waves )
- Quantitative analysis using ( Based on complex mathematical calculations, quantitative analysis makes it possible to anticipate the risk and return of a financial asset. )
Note : i'm following this tutorial for the moment to get an idea about building trading app's Trade APP
2
u/ajinata84 Mar 07 '22
i'm not relatively new to react, but i have some weakness in my react skill, which is i dont know where to start from. any tips on what to start first for react? like setting up navbar first and then something something something, i always got confused about that. any tips for plebs like me?
2
u/sp3cial_kas3 Mar 11 '22
Hi, I have 4 components: Header, C1, C2, C3. So I want to use the same Header component for the components C1, C2, C3.
const Header =()=>
{
<div>
<h1> Top Header </h1>
</div>
}
What I want is to use the component Header as the header for all the components, but with different text in the <h1> tags for each component C1, C2, C3.
I tried passing it as props but didnt work out. How can I do it?
1
u/ComunismoConSushi Mar 20 '22
Hi! I'm doing my first project in react for an assignment, I've been investigating file reving for static assets. So far I've managed to apply this on static images by putting them inside src folder, but I still have a logo and icon used in index.html which is in the public folder. Is it possible to Include logo and icon where react will Include them in reving when doing a build and still be visible to index.html?
1
u/Zefiron Mar 03 '22
Hello all,
I'm rebuilding our web remote control GUI for our company in react (very excited to learn!) - one of the hurdles is when using the remote control over a local network is that Google Chrome doesn't allow these request as it blocks insecure private network requests.
We want to make a PWA that can be downloaded and standalone and make these calls, are there any benefits or limitations in using either ajax / axios / or fetch that would hit limit calling to a local machine on the same network?
1
u/oOPassiveMenisOo Mar 03 '22
I was using react-ace for a text editor, theres a line
which goes to
does anyone know whats actually being passed here, if I wanted to use the newValue for something else would I be passing it something like document.getelementbyID("editor-id").innerHTML to pass the same content
1
u/setdelmar Mar 03 '22
In a MERN it is customary to have the
URLs for front and back ends to be each other's proxies in their
respective package.json files, correct?
Just wanted to confirm as am doing my first little MERN.
Thanks
1
u/Tixarer Mar 05 '22
I have a dropdown that filters the data returned from an api (the dropdown contains all the pokemon types and the api is pokeapi). There is an option for each type and an 'all' option that returns all the pokemon.The problem is that the 'all' option works but the others options for the different types don't work (they return nothing).Here's a Codesandbox of my code (it doesn't seem to return anything but at least there is the code).The filter is the second filter method inside the ol tag.I don't know what I need to modify inside this filter or if I should use a different method.
1
u/Creative_Race_1776 Mar 07 '22 edited Mar 11 '22
in chromedevtooks, How to look at the value of state variables in the watch view. everytime I try to look at the value of a useState variable x, it autocompletes to setX. I am
unable tonot allowed to use react devtoolsfor some reasonby policy, on my machine, so i have to work with the regular dev tools1
u/nwatab Mar 07 '22
Hello. I have a question about separation of concerns across custom hooks and presentation. Which one of these would you use? I use Pattern2.
1
u/quavoFE Mar 08 '22
Please help me before I lose my mind..
I'm new to react so forgive me for my ignorance...
I have a navbar component with three header items that I would like to be able to link to for different pages.
When I go to click on the item it says " 404 page not found " and after looking at the console it says " Failed to load resource: the server responded with a status of 404 (Not Found) "
I'm not really sure what could be the problem...
1
u/pixelmarbles Mar 09 '22
I'm new to React.
const [count, setCount] = useState(0);How is React able to set the value of a const variable?
1
u/Negative12DollarBill Mar 12 '22
I have a conventional javascript application which I want to convert.
It's a quiz and basically has three elements on the page:
I mean, that's the pseudocode version, but you see how it works: the user clicks start, the 'during' div appears, the 'before' disappears, the quiz takes place, when they get to 10, the 'during' disappears and the 'after' shows them their score.
How do I think about something like that in React terms? Do I flip visibility of those three divs like I do now? Remove/add them from the DOM? Have one master div which contains only the content relevant to the current stage of the process?
This is more about me learning to think in React than actual coding!
1
u/NickEmpetvee Mar 14 '22
Browser autofill values seem to not always trigger onChange on controlled fields. Any tips on how to resolve? Essentially, when submitting the below with the submit button click, the state field values get populated by the autofill. If submitting by putting the cursor in either field below and pressing
ENTER, it's not populated.The structure is basic:
state variables:
1
u/[deleted] Mar 14 '22
https://openweathermap.org/api/one-call-api#example
How would I iterate over a JSON object to dynamically create multiple components? And how would I save these values to a single state to update it? I need to grab specific values from the daily section. It has seven objects with the same info inside of them but for seven different days. I cannot use .map() or .filter() because at the very top level it's an object. I need these values to dynamically set the state in a single component.
I'm modeling the component to look like the AccuWeather daily section.
1
u/DroiD_1997 Mar 14 '22
Hello can anyone tell me how to display fares in each cell of calender in react like airlines do??
1
u/MisterCrispy Mar 15 '22
Preface: Reactjs + typescript. I'm primarily a C# developer so with my brain, class components just make more sense to me but I've been forcing myself to use functional components more and more for simpler items and such.
One issue I'm running in to with a new app I'm working on:
If I've got a relatively complex form with, say 30-ish or more fields, is it better to just use a class component or is it ultimately easier to create it as a functional component?
Side note: We can get into UX/UI discussions about a 30 field form on one page in another thread but this is how the customer wants it and they're the ones writing me checks. Sometimes the best argument you can give someone is to let them have their way.
1
u/Xyles Mar 15 '22
Hi, I have recently been trying to package a re-usable component for several of our applications to maximize code reuse. My question is - is it possible for us to have nested Redux providers?
1
u/Tixarer Mar 16 '22 edited Mar 16 '22
I'm working on an app and one of the file has 1200+ lines (link to the github file). Would dividing it into multiple files improve the performance of the page ? What is the best way to divide a huge file into multiple files ?
1
u/Physical_Lifeguard_9 Mar 23 '22
Can anyone recommend a starter package that already includes login/register screens, admin/normal users + optionally a `Foo` CRUD page? Looking to prototype something as quickly as possible.
1
u/Spiritual_Salamander Mar 24 '22 edited Mar 24 '22
Edit: Code block just isnt working for me...here is an example gist.
Gist
Here is some Pseudo code. Let's say this component initially shows 5 todos. I am on the desktop, and I push a button and this triggers to show 5 more todos, so the todos is now a list of 10 elements, not 5. When I shrink this down to SP size...it only shows 5 todos, and it shows 10 on desktop. Why ? What is the fix for this ? The logic for showing more Todos is in the TodoList component, is this perhaps the problem ? So it seems that there is now 2 TodoList components, that each have their own separate state and thats why the are not in sync.
1
u/Tixarer Mar 24 '22
I'm currently using styled-components with react and I want to setup a light mode / dark mode switch. I'm following this tuto but inside they put everything inside the app.js (the themeToggler function and all the content).
The problem is that inside my app.js I have all my routes setup and my button is not in the same file than the ThemeProvider tag that wraps my whole app so I tried to do it like that but idk how to import the theme from the child (header.js) to the parent (index.js).
1
u/anon2812 Mar 24 '22
How can I A/B test my Nextjs Frontend?
1
u/[deleted] Mar 25 '22
Using Zustand for all state management? Zustand is global state management. Is there any reason to not use Zustand for all state management. useContext was global state as well, so I don't use that anymore.
But how about useState for specific components? Or should I just be like, everything in Global state (Zustand) because its just easier that way? Or is it bad practice to keep state in global when its only used in certain components (but then again when things change, something that is only component state, might need to eventually go global).
So global state for everything?
1
u/scanguy25 Mar 25 '22
Is using the context everywhere for variables bad for performance or just considered an anti-pattern?
I have tried to use the composition approach, but my apps are often so many levels deeps it leads to very hard to read code.
1
u/N0213568 Mar 25 '22
I’m new here looking to learn React. Any recommendations for a good starting place?
1
u/ChipsTerminator Mar 29 '22
Hello, I have a question about mechanism of garbage collecting. Suppose I created a class object by useMemo, like following.
And I want obj to be completely destroyed after unmounted, should I need to reset all its properties to null / undefined or just change obj reference (like obj = null) ? Or react will automatically do it for me?
Any answer or advice is appreciated, thank you!
1
u/No-Strain-4782 Mar 29 '22
Hello, since I am a beginner react learner, I cannot grasp the idea of changing states. This is why I am struggling with the following problem. When the "toggleIsShown" function is called, I want to toggle the first element of "isShown".
const [isShown,setIsShown]=React.useState([false,"Hide"])
function toggleIsShown(){
setIsShown(prev=>{
prev[0]=!prev[0]
return prev
})
}
3
u/ZeAthenA714 Mar 18 '22 edited Mar 18 '22
Hey everyone, new to react here (using Nextjs specifically).
I have a basic auto-complete input where I want to show suggestions that comes from an API. So user type in a string, there's a request to the API which answers with a list of suggestions that I can display.
The things I have to be careful about is 1) I have to wait a bit after the user type in something to avoid making a query to the API for every single keystroke and 2) I have to make sure only the last query made is actually taken into consideration (because the answers to the queries might not arrive in order, and I only want to display suggestions for the current input).
I think I see how to do all of that, I can use setTimeout to wait a bit before making a query (but then I have to make sure every new keystroke cancels the existing timer), I can compare the request made to the current input value to sort through incoming API answers etc... but it feels a bit cumbersome.
Is there maybe some best practices or library or maybe even some react feature that I don't know about which could help in that situation?
Edit: found the solution right here: https://dmitripavlutin.com/react-throttle-debounce/#:~:text=debounce()%20function%20accepts%20the,passed%20after%20the%20last%20invocation. Works perfectly!
3
u/Sabiancym Mar 22 '22
Are there any form libraries for creating a typeform style form/quiz? Something with logic?
I want to have a questionnaire that will show rough pricing estimates upon completion. Typeform works fine, but the free tier is limited.
2
u/isbtegsm Mar 10 '22
Hi, I'm watching Sonny Sangha's tutorial Let's build Instagram 2.0 and since I'm totally new to all that auth stuff, I'm wondering a few things:
2
u/[deleted] Mar 15 '22
I’m finally somewhat competent and can work independently on a large repository… now what? How do I get from being a programmer to a swe? Do I need to learn backend and sre/devops/ci/cd stuff as well?
2
u/Trung020356 Mar 19 '22
Thought I'd try asking here. I posted this in a Discord channel, but been having issues getting started with after using npx create-react-app.
Erm. Anyone have experience with getting started with React? I'm just following along using npx create-react-app, and then just doing npm start in the folder. It hosts everything at http://localhost:3000/, but whenever I refresh the page to see the changes I've made to App.js, it won't update the page at all. :/ On Windows 10 using Ubuntu 20.04. Been googling for a while and tried setting up some .env file. Gonna pick at it later, but thought I'd try asking here. Then there's also issues with webpack taking a long time to compile.. Terminal looks something like this.
npm start on folder created from npx create-react-app on Windows 10 using Ubuntu 20.04
1
u/Dazzling_Walk9777 Mar 01 '22
Hello, I'm new to ReactJS, and have the following question,
I have a Component, I'm grabbing a JSON using fetch and trying to display that value, nothing fancy. It seems like the fetch occurs after the return statement. Isn't Fetch/Then supposed to wait?
Thank you, code below.
function Test() {
fetch("http://localhost:8080/examples/servlets/servlet/TestServ")
.then(
response => {
response.json().then(function(data) {
var gg = data.name
console.log(gg);
});
})
.catch(err => console.log('Fetch Error :-S', err));
return (
<>
<h1>HELLO {gg} </h1> </> ); }
1
u/Nehatkhan786 Mar 05 '22
Hey guys need help with function undefined error which is chaining error. I am creating a simple e commerce site in react in which there is cartItems array when a user click on a add to cart button its store the item in the cartItems array.And it works perfect file.
Now the problem I am facing in cart page to show cartItems. I import the cartItems array from the context as I am using useContext and useReducer hooks for the global state.
And in return statement of the cart page I using the code which throw error.
{carItems.length === 0 ? ‘Show Item’ : ‘empty’ }
This gives error- uncaught- TypeError cannot read properties of undefined (reading ‘lenght’)
I understand this issue because html mount first without the cartitem.
So after googling I tried this- {carItems?.length === 0 ? ‘Show Item’ : ‘empty’ } But this behaves weird, when the cartitems in empty than also it show ‘Show Item’
PleSe help me out, i am really frustrated now
1
u/Nehatkhan786 Mar 05 '22
Its done! I was not providing the cartItems array in context provider lol. It was such a silly mistake
1
u/RichieRich685 Mar 06 '22
Hey, I'm a beginner in react js. I known the fundamentals and most of the hooks. I'm able to create small Web apps, like calculator, weather app. But I want to improve my react skills more and I want to learn to build full stack react app, I do not have much experience with full stack app. Could you give me any suggestions or resources to improve my react skills? What projects can I do? Please help
1
u/pixelmarbles Mar 09 '22 edited Mar 09 '22
I'm learning how to useReducer's with a todo list app however I noticed that when I toggle the 'completed' value of todo using its old value in the reducer (and negate), it doesn't apply the change. But when I pass the negated value in the payload from the calling function, it applies the changes. Why is that?
Here's my Todo component:
}
And here's my reducer:
}
The areas of concern is the todoToggled() function and "todo/toggle" action.
1
u/Patrickstarho Mar 15 '22
I need help. I want to pull data from Reddit api and then use that data to get sentiment from post titles using a rapidapi.
I have most of it set up but I ran into so many issues. It seems that the function returns before all the sentiment can be added and it renders with not all of the data.
I need help, I’m using use context to store the results so if anyone can tutor me or give me a hand I’ll pay $20/hr. Thanks
1
u/Eight111 Mar 16 '22
How can I force the <app> to remount?
I have inside <app> a <navbar> and routing to <home> and <profile>
I also have custom hook inside <app>.
I want the <app> to remount whenever I click on the home link at navbar so my custom hook will reset, kind of page refresh without actual refresh..
1
u/Maximum_Government_5 Mar 16 '22
Hi!
Following a guide to set up React and PowerBI Embedded, but the React example gives a syntax error and I don't really understand enough React yet to fix the syntax. I would think there should be a fetch in there towards the API as well, not just var url?
CodeSandbox
1
u/cokert Mar 17 '22
This came up in a PR just now and I don't know which is "better". The component is essentially this:
The PR comment was to change it so that in the parent, you checked the
showvalue and conditionally renderIndicatorlike this:{show && <Indicator />}.It's (functionally) not much of a difference, but IMO, the way it was written should be preferred since the parent doesn't have to overly concern itself with
Indicator. It's pushing "the concern about showing the indication" down to the component that should care. Pulling that concern up into the parent feels like mixing concerns. You might could argue it's More Efficient to just not render anything at all if the component is going to do nothing (ie, skip rendering the component completely -- don't waste time just to have it display nothing), but that seems like a much too premature optimization.The component in question really is that trivial, but we're displaying this same indication in a few places. Hence it being a component in the first place. And given that we're displaying it in a few places, that gives more weight to my argument -- if we ever want to display something for the false case, we'd have to touch all the places where we're using the component to get rid of the conditional rendering.
Anyone have any thoughts one way or another here?
1
u/FrisbeeTee Mar 23 '22
Facing an issue where the method in the class does not render the needed div only if it's inside the OwlCarousel component.. I'm running another carousel on the same site with the same exact logic and it works fine, and it is not causing a conflict as the second one still doesn't work even if the first is not mounted..
I have json-server running, and fetched the information of the img that will be the slides of the carousel.. after fetching the information and adding it to state, I'm doing a map method (getCarouselSlides) that works fine in the render() function, but for some reason doesn't work inside the OwlCarousel component (or the ReactOwlCarousel).. I know the method getCarouselSlides() works cause it does everything it should as long as it's outside the component.. also tried returning a <h1> tag and it worked fine..
This is all the code in the jsx file: (Updated so that every slide is its own component to match the first working carousel, same exact situation)
https://jsfiddle.net/fse0dwvr/
1
u/foldingaces Mar 23 '22
Hello, I have a pretty straightforward question about best practice when setting some kind of error message/message/toast. Is it better for a function to set State, then have a setTimeout in that same function that will later revert the state. Or is it better to have a function that sets state, and a useEffect that will have a setTimout to revert the state back.
Here is a small example: https://stackblitz.com/edit/react-zuvaei?file=src/App.js
Option 1:
Option 2:
Or is there another 3rd option I'm not thinking about that is best practice?
1
u/setdelmar Mar 23 '22
I just learned ReactJS enough to feel I could work with it not too uncomfortably and made my first MERN that implemented Editor.js as a CMS and deployed it on Digital Ocean (another first). I am checking out work online though and finding it quite common for them to advertise a position for ReactJS when they really want React-Native which I have not yet learned. Trust me i am asking this out of ignorance. Should I immediately start learning React Native or is there a lot of work out there for plain old ReactJS and learning native could wait a little?
Thanks
1
u/NoWimple Mar 25 '22
I have a question about styling.
Say my folder structure is like this...
/components
--/ComponentA
----ComponentA.js
----ComponentA.css
--/ComponentB
----ComponentB.js
----ComponentB.css
/pages
--/PageA
----PageA.js
----PageA.css
Is it bad practice to define a style rule in PageA.css that will apply to elements in ComponentA and ComponentB?
Certain parts will have similar styles but I dont want to duplicate my code.
Sorry if this is a newbie question, I have trouble maintaining separation without repeating myself.
1
u/[deleted] Apr 08 '22
Hello, not completely new to react, but Im working solo on a few internal apps and need to bounce some ideas off of community. I recently migrated an app to redux toolkit and am not using any middleware, simply using createslice and createAsyncThunk. Is this actually sustainable or should i be considering middleware?
0
u/[deleted] Mar 25 '22
[deleted] — view deleted comment
0
u/[deleted] Mar 14 '22
[deleted] — view deleted comment
0
u/[deleted] Mar 21 '22
[deleted] — view deleted comment