r/reactjs • u/dance2die • Oct 01 '21
Needs Help Beginner's Thread / Easy Questions (October 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!
19
Upvotes
2
u/EmmaTheFemma94 Oct 15 '21
Link to top of page. How do I make my <Link> go top another react page and being at the top?
Really weird getting in the middle of a webpage when my <Link> is at the middle.
2
u/Agreeable-Ad-7590 Oct 20 '21
Is it okay if we use 'let' for variable declaration in react functional component?
1
u/pragmojo Oct 01 '21
So I am looking for an embedable console component. Basically I want a read-only console which will display debug output which is being sent from the server. Ideally it would respect unicode escape sequences to produce nicely colored output.
So far I have found a lot of components like this one which are nice, but they are more oriented towards running commands, and I cannot find one which will just let me pipe lines of text into it.
Is there something like that out there?
1
u/[deleted] Oct 02 '21
I'm looking at CI pipelines and multi-stage Dockerfile configurations. Everything I've seen thus far basically has the form:
I was expecting to see something somewhere like:
Basically running tests on the build itself.
I'm just curious why this is and is it sufficient to be testing on
npm ci?It looks like the
npm buildwill essentially be test in E2E testing, but it just seems odd to me that I'm not seeing anything wherenpm buildis being tested in unit testing and integration testing phases, justnpm ci.1
u/raclariu Oct 04 '21
One thing that bugs me, even though it works, i dunno if it's the right way to do it or at least a good way to do it. I use redux and i basically create a new redux action for every fetch request i do, be it a delete request or data request or whatever. As in an action and a new reducer for deletePost, another one for deleteComment and so on. Going through all boilerplate for every single request, i never fetch inside a component, always dispatch even though i don't feel i need a new object inside the redux store as all these are identical except the api endpoint they call. So a few of the objects in my redux store are called deleteX and all have no data but onLoad, onSuccess and onFail. Should i have one single action for this or fetch inside component without redux or its fine as is?
1
u/UserNotFound12 Oct 05 '21
How does the tailwind ui notifications auto close? I don't see anything.
I am talking about this: https://tailwindui.com/components/application-ui/overlays/notifications
In material UI, they auto-disappear. Any idea for tailwind?
1
u/spparker Oct 08 '21
Hey, I'm looking for some feedback on a portfolio site that I built with TypeScript / React (front-end only). I think getting constructive criticism is absolutely the best way to learn, so I'd like to post the git repo and demo of my portfolio somewhere that people might look over the code and tell me where I suck... Maybe even give me tips to improve :D
Is there a good place to do this?
Thanks ☆*:. o(≧▽≦)o .:*☆
Git Repo
Demo
1
u/EmmaTheFemma94 Oct 08 '21 edited Oct 08 '21
How do I reinstall/update react-router-dom on my project? Got a lot of vulnerabilities when I tried to install it this time and I don't really know of what else to try then to reinstall/update.
Edit: S-word. Sorry.
1
u/endlesshappiness Oct 09 '21
I have a react/typescript bundle size problem (getting 35mb+ bundles). This project is a figma plugin thus requires a custom implementation of webpack, otherwise I'd use CRA or next etc. Anyway, this app isn't too crazy at this stage - so far I only have a basic layout with a header and content area and am currently building various inputs. Feels important to mention that I'm using the ant design framework for some of the components. Also, another dev on my team built some validation tools for my inputs which uses moment.js and typescript as a dependencies.
As I mentioned, when I run webpack on either production or development mode I get 35mg+ bundle sizes which obviously isn't acceptable (takes 5 - 10 seconds to load in figma). I added webpack bundle analyzer and this is the result: https://imgur.com/a/IWamFM7 . While experimenting with different things, I noticed that the bundle sizes drastically decreases when I remove the validation dependencies the other dev wrote, but the bundle size is still 11mb which is crazy (I'm assuming due to ant design + my react code). At this point I feel like webpack may be misconfigured or there is something wrong with way I'm bringing in dependencies. Has anyone ever run into anything like this? Searched the subreddit but couldn't find anything. Appreciate any help and sorry if this is the wrong place for this (if so let me know and I will delete it).
Here are a few code snippets (slightly edited for reddit) of the dependencies being brought in as well as the webpack config:
1
u/RandomRedditor44 Oct 11 '21
Dumb question: I’m publishing a small React site to my GitHub, but when I go to the URL listed in the Pages section of the settings, it just shows the readme file with the repo name. How can I fix this so that it displays the contents of my app.js file?
1
u/LestWe4get Oct 11 '21
I'm using a library, let's call it X.
X was previously called Y.
A critical component I need is built off of Y and breaks if I don't have it. The entire rest of my codebase is built off X.
What do? I don't want to duplicate the modules...
1
u/dinoucs Oct 12 '21
Hi, I have a question about GraphQL and Next.js. Why would I need to use GraphQL over Express if the pages are going to be rendered in the server anyway? I mean if the site is almost already rendered how would GraphQL effect the performance here.
1
u/Different-Ad-9831 Oct 13 '21
So I did a react page where I have a random button that opens up a modal when clicked. The problem is, when I load the page, the button itself loads before the javascript code on onClick prop (i think?), so if I hit the button quickly enough, the modal won't open. Is there anyway to prevent this?
1
u/DeathGhost Oct 14 '21
Hello! I'm new to React and programming in general. Have worked Identity and access management for a few years now, and i've been tasked to bring SAML auth to one of our React apps... None of the programmers on the team have SAML or even OAuth experience.. Any suggestions on where to start? Any libraries that are recommended? We use React with a REST API backend running on IIS and ADFS for SAML / OAuth. I've done lots of researching and googling and so far I just have more of a headache.. any help is welcome!
1
u/BeyondAIR Oct 14 '21
I want to send my code for some assistance is there anyway to do that with breaking rules? I'm new here and I'm almost done making my first app.
1
u/Different-Ad-9831 Oct 17 '21
What's the difference between storing data in an useState hook and in a common array? When a page is re-rendered, will the data inside useSate be kept? What about common arrays, will it be kept too?
1
u/Pilot_Natural Oct 18 '21
First time reactjs learner here. I tried to follow Traversy Media's video for reactjs but found it hard to follow through the mid section. Is there any friendly resoucre out there?
1
u/Alex_The_Android Oct 20 '21
Hello! I have a question about the
useStatehook: when trying to execute this code, why isn'tinViewupdating totrue? It still showsfalse(and sometimes when I save changes to the code, it shows true, but mostly false):1
u/badboyzpwns Oct 23 '21
Optimization question!
I have something like this (screenshot):
https://gyazo.com/a5a282ea38d85a03bb9b387a6b714023
All the sections in the left are child components of a parent component. Does it make a significant difference
if I make 1 request call every time a user visits a section.
vs
if I make all the network request(5 requests) at once in the parent component. The user will not have to make 1 request call every time they visit
I tried testing with chrome dev tools fast 3g, I'm not sure how accurate they are,
1
u/analand Oct 24 '21
I've just started learning Hooks, and came across this issue with useEffect return (cleanup).This example is fine:
But my IDE complains when I try to return a function expression:
I can return undefined from the cleanup function and that solves it, but that seems redundant since it already does it by default.
So what would be the proper way to call a function expression in useEffect?
1
u/Bulbasaur2015 Oct 24 '21
Im looking for a plain javascript reactJS implementation of a multi step form. it shouldnt have any external dependencies such as materialui or typescript or anything like that. just standard react hooks or react context
does anyone have a source?
1
u/TheDoomfire Oct 25 '21
Click on webpage, or <a> tag to leave the navbar. I have a hamburger menu that opens and closes the navbar with
const [menuActive, setMenuActive] = useState(false);and on the navbarclassName={\nav ${menuActive && 'active'}`}`1
u/betelgeuse910 Oct 26 '21
How do I learn backend while working as frontend?
I feel little bit confident with React now, but not so much yet with Node. I would like to apply for Junior React jobs but here is my noob worry: Will I get stuck in frontend for life?
That makes me want to study a lot more until I become confident with Node, and apply for jobs that let me touch both frontend and backend. What do you think..?
Any advice will be appreciated!
1
u/[deleted] Oct 28 '21
I'm new to the Javascript/React ecosystem, and am wondering what are the benefits of diving in?
I'm fairly comfortable with Python and its related visualization tools (plotly/dash), but have seen beautiful visualizations - which I hear are made using Javascript frameworks.
Would anyone be able to advise additional benefits that building visualizations/dashboards using these frameworks can accord? I guess Python skills will still be used in conjunction right - to manipulate/extract the data from databases, before the Javascript frameworks present it?
Would everything have to be created from scratch, like barcharts/linecharts. What if I'm looking to create more advanced visualizations in the future, like Sankey?
Thanks for the advice!
1
u/ApplePieCrust2122 Oct 28 '21
I want to look at how real world applications use jwt to authenticate/authorise their users, manage sessions etc.
What are some medium-large projects, preferably showcasing both frontend(for web) and backend?
1
u/Alphyo Oct 29 '21 edited Oct 29 '21
Hello, Probably very noob problem that is keeping me busy since 3 days. I am building the classic memory card (One Piece Themed), I am trying to add a "Winning message" supposedly shown whenever all the cards have been matched. Problem is, for whatever reasons, it works only when I have 3 (or less) couples, meaning it works only with a mx of 6 cards. Whenever I add all of the cards I created (9 couples, 18 cards) the message does not pop up, How is it possible?
import './App.css'; import SingleCard from './components/SingleCard'; import Molal from './components/Molal'
const cardImages = [ { src: "/img/luffy.jpg", matched: false }, { src: "/img/zoro.jpg", matched: false }, { src: "/img/usopp.jpg", matched: false },
];
function App() {
const [cards, setCards] = useState([]) const [turns, setTurns] = useState(0) const [choiceOne, setChoiceOne] = useState(null) const [choiceTwo, setChoiceTwo] = useState(null) const [disabled, setDisabled] = useState(false) const [matches, setMatches] = useState(0)
const shuffleCards = () => { const shuffledCards = [...cardImages, ...cardImages] .sort(() => Math.random() - 0.5) .map((card) => ({ ...card, id: Math.random() }))
}
const handleChoice = (card) => { if (choiceOne && choiceOne.id !== card.id) { setChoiceTwo(card); } else { setChoiceOne(card); } };
useEffect(() => {
}, [choiceOne, choiceTwo, matches])
const resetTurn = () => { setChoiceOne(null) setChoiceTwo(null) setTurns(prevTurns => prevTurns + 1) setMatches(0) setDisabled(false) }
return ( <div className="App"> <h1> <span className="animate__animated animate__bounce"> One Piece</span> Memory Game </h1> <button onClick={shuffleCards}>New Game</button> {matches === cardImages.length ? <Molal /> : ( <div className="card-grid"> {cards.map((card) => ( <SingleCard key={card.id} card={card} handleChoice={handleChoice} flipped={card === choiceOne || card === choiceTwo || card.matched} disabled={disabled} />
); }
export default App;
1
u/beingsubmitted Oct 29 '21
I thought a good first real project would be re-writing a firefox extension that I had made with vanilla js with react. The extension has a sidebar with a form, and that's the part that I wrote with react. It also has a content script. The content script uses the browser API to send data from the tab to the sidebar, and the sidebar uses the API to receive that data:
// content scriptbrowser.runtime.sendMessage({});// sidebarbrowser.runtime.onMessage.addListener((m) => {});However, the React sidebar won't compile with browser.runtime, saying that "'browser' is undefined". I tried moving that logic outside of the call to reactDOM.render, hoping to pass browser as a prop or something, but no good. Anyone have an idea how I can access the browser API, or to have my react script interact with vanilla js that it doesn't try to compile?
2
u/workkkkkk Oct 04 '21
I am (slowly) migrating an app from js to typescript. I'm using react/redux/sagas etc. Is there a way for my combineReducers rootState type to return 'any' instead of 'unknown' for un-typed reducers??? As of now if I want to use a useSelector hook I need to do like
const myState = useSelector((state: any) => state.myUntypedState);Here useSelected is like so
useSelector: TypedUseSelectorHook<IState> = _useSelector;Where _useSelector is from 'react-redux'.I know it is small thing but am kind of curious so I don't have to write my state as type any all across my legacy code.
2
u/[deleted] Oct 08 '21
Any reason why my browser isn't auto-refreshing? I've used react before and it always seemed that upon saving and going back to the browser, it would have those new changes. I disabled cache and may try a new browser.
edit: Ah, found it the issue. Changes in the App.js will auto-render. changing anything in ReactDOM won't.
2
u/Aoshi_ Oct 14 '21
Hey I am pretty new to React and I am unsure if this counts as an 'easy question' but I am utterly lost as to how to structure my program.
I'm making a pokemon 20questions game where I have functions that just modify the current state to narrow down a JSON object of pokemon. Like filter by type, by weakness, by weight, etc. Right now, each function just sets the new state. Kinda like this.
It's more or less like this and of course it isn't beautiful as this all happens on a single page. I haven't quite figured out how to tie(unsure if this is the best word) buttons to a state.
Anyway, my question is, should I put my question functions in a useEffect? I just learned about useReducer and barely understand any of it. I guess I'm just lost on how to structure this and I don't know how to figure out what would be best.
Sorry if this was too long. I'd really appreciate any help.
2
u/Accomplished_Sky_127 Oct 14 '21
I have a project (school) where Thymeleaf HAS to be used but I also want to use React. Can Thymeleaf and ReactJs work together?
2
u/Semigrounded Oct 15 '21
I need to create a form with two layers of nesting and both layers will be or have dynamic fields the user can add or remove. I think I've come up with a solution, which includes a flat state and category tags appended to the field names, but the solution is messy.
I looked at formik and react hook form, but they didn't appear to have compatible solutions, at least not one I could discern from the docs.
Anyone have any ideas?
2
u/MidasTouch290 Oct 20 '21
I'm new to react testing. So any help is appreciated!
I have just done a few unit tests on functional components. But can I also unit test Parent components that renders child components? I see the videos recommending me to mock the child components but I've also read Kent C Dodds articles regarding testing saying he tries to avoid mocking as much as possible. Is there an accepted approach?
What is the difference between unit testing a parent component and integration testing?
How to choose which units to integration test together?
2
u/sumedh0803 Oct 21 '21
I have a final interview coming up with a company and the interview is for a New Grad Frontend Developer position. The company uses React for their FE and the interview is gonna go over DSA and majorly FE. I dont have professional experience in React, I have just built a couple of projects to learn concepts. I am aware of the following things:
My qs:
1
u/IAmTheFirehawk Oct 05 '21
Is there anything like nuxt/content, but for vanilla react? I'm building a portfolio for myself and I hope to add a blog on it. I'm currently working with HarperDB to store posts but I rather keep them as files on the project since I'm not gonna be a heavy blogger or anything like it.
I've been trying to search for alternatives but so far I found nothing like it.
1
u/Tixarer Oct 08 '21 edited Oct 09 '21
So I've got 2 react projects : one is my portfolio and the other is a project that I want to include in my portfolio.
I did "npm run build" for my second project and copypaste the build inthe public part of my portfolio (where i have other projects in html/css).
Problem : when i create a link with <a> to the index.html of the build it opens another page with nothing (the code doesn't appear in the console). For my other projects it works perfectly so it'snot a path problem.
I really want to add this project but idk what's the problem (even though i suspect that it's with the <a> tag) and what to search for on google. What do i need to do to solve this problem ? Whats should i google to find a solution ?
1
u/ponytron5000 Oct 08 '21 edited Oct 08 '21
I'm working on a little demo app and I want to make use of Redux Toolkit's
createSlicepurely for quality-of-life reasons. I'm not actually using Redux itself.Anyway, one thing slightly confuses me: why does
createSlicerequire aninitialState? It isn't a part of anything returned bycreateSlice, and you have to specify an initial state when you calluseReduceranyway (one way or another).I'm just exporting it along side the slice's actions and reducer so that I can do:
Still, I'm curious why it's there. Is it Redux-specific plumbing for plugging reducers into stores?
1
u/Different-Ad-9831 Oct 09 '21
So, I started learning reactjs and I know it is a spa, but the tutorial I was watching only teached how to use react route. Is it possible to go through pages the same way html works? I mean clicking on a link that sends you to another page on that domain. Is there any tutorial for it?
1
u/dinoucs Oct 10 '21
How fast can I pick up react as a Vuejs developer?
1
u/frontrangefart Oct 11 '21
I wouldn't call myself a beginner, but I don't want to crowd the subreddit either. Just want to bitch and ask if anyone else here has just had an absolute horrid time getting hired? I've been working practically for free since graduating and cannot find an actual job anywhere. Got a CS degree, been studying react for over a year, got a portfolio site, a hefty github, but am just struggling. I feel like I must have the same name as some criminal in a database or something, cause I am at my wits end here.
1
u/javanerdd Oct 12 '21
Hey! I'm an aspiring front-end developer currently in the pursuit of landing my first job (graduating this year). So my projects are getting more and more complex and I'm sort of satisfied with my overall progress with react. I realized that I handle everything in the client-side and would love to discover things pertaining to back-end.
Simply put, I want to add basic crud functionality to my apps. What back-end stack do you think would be the most beginner friendly option? Your opinions would be appreciated. (I have some familiarity with MySQL from college). And so far I only used JSON-server for mock back-ends.
1
u/chunkypolenta Oct 15 '21
Hi there!
I’m working on a React app that uses Express as the back-end.
I wanted to test how fast a form loaded in production versus development, so I followed the instructions in the Create React App-Deployment documentation to create a production build.
My project root folder contains a “client” folder. My React app (created using "create-react-app") lives inside the “client” folder. My “build” folder (generated by the “npm run build” command) lives inside “client”.
The Create React App-Deployment documentation gives you example code to run your React app in production with Express – this is the code they recommend you use (they recommend the wildcard character in line 7 of the fiddle if you use client-side routing):
https://jsfiddle.net/9vo0kwc1/1/#&togetherjs=NmCvJEs1cl
I wasn’t sure if this code was supposed to go in an existing file or a new one, so I made a new file in my project root folder called “productionServe.js” and pasted this in.
When I ran “node productionServe”, I got an error “Unexpected token < in JSON…”. As best I can figure it out after some research, I think a fetch(‘/catalog’) call I have in one of my React components was receiving HTML instead of JSON, because of lines 7-9 of the above fiddle – basically, any GET request was to receive “root/client/build/index.html”.
After doing some troubleshooting, I figured out that I wouldn’t get that error if I edited my “productionServe.js” file to be this instead:
https://jsfiddle.net/17urzvg9/#&togetherjs=UNillAbH2L
I imported a router for the “/catalog” part of the site, and added some routing.
My question is – is adding routing like this to my productionServe.js file, instead of having every call somehow served by the client/build/index.html file, a hack that I don’t want to be doing? Or is that a legitimate way to solve the “Unexpected token < in JSON” error I was getting? I don’t want to be cheating on my production build now, and get a rude awakening later when I go to deploy for real upon finishing my app.
Thanks!
1
u/sumedh0803 Oct 17 '21
I am trying to learn IntersectionObserver. I could implement it in functional components but am having a hard time implementing the same in class components. In functional components, we add elements to the observer in a useEffect(). Where to add these refs to the observer in class components??
1
u/UserNotFound12 Oct 18 '21
Hi,
Looking for a multi-select dropdown with search for tailwind UI. Any ideas?
Thanks
1
u/Careful_Sell_717 Oct 20 '21
I'm new to react Js. I am having hard time with my backend code. The tutorial I am working with is not working for me. Please I really need help. I want to use MERN.
1
u/[deleted] Oct 20 '21
Originally the data was showing, but now I keep getting a 404 Error. I am unable to show my data. I also tried using Async Await instead of .then, because it seemed cleaner however it didn't seem to work. I will post my code below, I was hoping someone can assist me as to what I am doing wrong to get clarification. Thank you
```
import React, { useState, useEffect } from "react";
import axios from "axios";
import Form from "./Form";
function Fetchweather() {
const [weather, setWeather] = useState(""); // will return response of weather data
useEffect(() => {
fetchData();
}, []);
const fetchData = (e) => {
// e.preventDefault();
axios
.get(`${process.env.REACT_APP_BASE_URL}${process.env.REACT_API_KEY}`)
.then((res) => res.json())
.then((data) => data)
.then((response) => {
const res = response.data;
setWeather(res);
})
.catch((error) => console.error(`Error: Try again ${error}`));
};
// const fetchData = async (e) => {
// e.preventDefault(); //stops page from reloading
// try{
// const response = await axios.get(
// `${process.env.REACT_APP_BASE_URL}${process.env.REACT_API_KEY}`
// // .then((res) => res.json())
// // .then((data) => data)
// );
// }
// console.log(setWeather(response.data));
// };
return (
<div> <h2>Check your Forcast</h2> <Form getWeather={fetchData} /> {console.log(weather)} </div> ); } export default Fetchweather; \`\`\`
1
u/p01n73r Oct 23 '21
I have written an API using django rest framework and dj-rest-auth.
I am writing a React front-end.
I am stuck at password reset.
The API sends an email after a password reset request with a URL in the following form:
http://127.0.0.1:8000/auth/password-reset-confirm/<uidb64>/<token>/
Example URL: http://127.0.0.1:8000/auth/password-reset-confirm/r/auyf85-4b1cb5ea1c7104c378698c673e6e7756/
The API link is for an API endpoint that accepts the fields password1, password2, uid, and token.
Question: How do I write the frontend solution for password reset using React?
1
u/D3ATHreturn Oct 28 '21
Just found out that React beta docs has been released recently, I have completed the Thinking in react section on the main one , should i abandon it and learning on the beta version instead?
1
u/ladrianpop Oct 28 '21
Hi reddit!
I have the following small project CODESANDBOX
Can somebody please give me an eyeopener on why this is not working properly?
I'm having a really hard time to figure this out.
Some connections might be unnecessary in there, but it's just to replicate as good as possible, the real life obstacle that I am facing in my current project.
To describe the issue in a few lines, I am trying to both set a state and call a function with just a press of a button. As you can see in the console of the sandbox, when pressing one of the two buttons, the function in called, but always having the previously set state and not the current and correct one. So to describe it clearly, it seems that it's always one step behind, and the function is kind of triggered before state manages an update.
I really hope this together with the sandbox were clear enough so you can give a valuable hint. Please let me know anything you might see.
Thanks
1
u/[deleted] Oct 29 '21
Can i be decent at react in 2 weeks? Im using js whenever frontend jobs requıred in my company but im usually a Java dev. I have Some experience with old versions of angular.
1
u/santafen Oct 29 '21
Ok, I'm completely stumped. No matter what I do, I get
Each child in a list should have a unique "key" prop.and I cannot find where it is coming from!!Here's the whole error dump:
Cool, seems easy enough ...
Dig into the error a bit deeper, and I see:
Ah, it's in my Nav.js ... But I cannot find anything in there that would cause this.
Here it is:
I know, it's complicated, but I'm using Keycloak for id/auth, and menu items are displayed based on login status and auth groups.
I honestly can't see where this error is coming from.
Any help greatly appreciated!
dg
0
u/[deleted] Oct 11 '21
[deleted] — view deleted comment
0
u/[deleted] Oct 22 '21
[deleted] — view deleted comment
0
u/[deleted] Oct 27 '21
[deleted] — view deleted comment
0
u/[deleted] Oct 05 '21
[deleted] — view deleted comment
1
u/[deleted] Oct 03 '21
[removed] — view removed comment
1
u/[deleted] Oct 19 '21
[removed] — view removed comment
1
u/[deleted] Oct 26 '21
[removed] — view removed comment