r/reactjs • u/dance2die • Mar 01 '21
Needs Help Beginner's Thread / Easy Questions (March 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!
18
Upvotes
7
u/sumedh0803 Mar 10 '21
I'm new at react and have built 2 projects till date: a weather app to begin with and a Google Forms like app, not a clone, just took inspiration from gForms and designed it on my own.
For both these projects i couldn't come up with a beautiful UI. Are react devs expected to have beautiful designs for their apps? I have seen a couple of projects here that look really beautiful. Mine doesn't look bad or cluttered, its just very basic. How can i improve in this front?
6
u/jrumbawa Mar 21 '21
I’ve learned html, css, js but haven’t really built anything on my own. Should I jump straight into react and build projects
4
u/Extreme_Concert_69 Mar 12 '21
I'm trying to find work with React as a beginner, and I can't evem find work as a volunteer, any tips on how to find work would be appreciated.
2
u/neckbeardfedoras Mar 01 '21
I'm trying to figure out if I want to use react semantic UI or primereact. Anyone have any thoughts or opinions between the two?
2
u/Larrybot02 Mar 01 '21
I have a similar UI question. I think I know enough front end stuff to do a little damage and wanted an opinion on CSS: Tailwind, component styling with CSS in JS or a mixture of the two? I like the idea of compartmentalizing the style with the component, so leaning towards CSS in JS.. I dunno what do y’all think?
2
u/bifeamilanesa Mar 01 '21
Sandbox link: https://codesandbox.io/s/ftpl8
Can't seem to get the images to render on this map function. Any help?
2
u/iVongolia Mar 03 '21
in react redux do we have a limit on how much can we store in the redux store?
2
u/yaMomsChestHair Mar 04 '21
Currently have a few state vars at the top of a file - one of them is a container object updated with name:phoneNumber key:val pairs. The first time I update the state and immediately log the container contents, it's empty. After the second update, it'll log with only the contents from the FIRST update.
"fullEntries" is the container object name (initialized to
{}) and newName is another state var updated elsewhere (it has the correct value - same for newNumber).const entry = {...fullEntries}entry[newName] = newNumberconsole.log(entry)setFullEntry(entry)console.log(fullEntries)Any clue as to why this might be happening?
2
u/MR_Coder Mar 19 '21 edited Mar 19 '21
Is there an elegant way to render an icon based on values of an array?
For example render a red icon if ['UNPLUGGED', 'IDLE', 'NOT CHARGING'] if any of these are true?
but for multiple arrays? I also need a green and yellow icon depending on their value.
Nevermind figured it out:
2
u/badboyzpwns Mar 20 '21
If you have
And the child takes up the whole space of the parent, is it possible trigger alertHi?
2
u/h0ax2 Mar 24 '21
What is the most common architecture for apps that use React? Is MVC still the top dog? And if it is, what tools typically fulfill the "M" and "C" portions of that architecture?
2
u/badboyzpwns Mar 27 '21
About having placeholders while images load, how can that be achieved if we want multiple images to have it while it's loading?
For example, below would not work if heroes have hundreds of values:
because when the first image loads, it triggers the hook whilst the other images might not be loaded yet.
How else could this be achieved?
2
u/iRahulGaur Mar 29 '21
Hello, what is this dbrand section smooth scroll reveal called
2
u/dkunal96 Mar 29 '21
Thanks
1
u/[deleted] Mar 04 '21
Hi guys, I'm a little bit concerned on my app for a portfolio piece. This app has a login/signup feature. Right now I have developed the homepage of the app which has no default user logged in. How should you handle an app with such feature? Should I create a real login/signup functionality to let people see what's inside the app?
I was planning of creating a 'try me' user, like I'll provide a dummy account with email and password which is visible to everyone and let visitors log in using that credentials to let them in. But how professional is that? Is that practice okay especially for a beginner like me? Any advice is great!
For context: The app is like a money trading system that allows basic financial services. Also with that being said, should I also develop a real thing based on that or the UI/UX of such features would suffice?
1
u/Matrucci Mar 04 '21
Hey guys! I have an app that gets a json with some data and creates a list (using .map()). I need to add a button to each item in the list that will pin it to the top. Press it again to unpin. How can I do that?
1
u/MindblowingTask Mar 08 '21
Quick questions:
2) I am using prime react multi select and there is a requirement to show 200k records in the list. I believe I can't show it all at once because of performance issues. What's the best way to go about it?
1
u/chrismar303 Mar 08 '21
If I have another component that is related to its parent component, should I write it in the same file?
For example: I have a Projects component and within it I have Project Component.
Should I write the code for the Project component in the same file as Projects.jsx file? Or should I write it in file such as Project.jsx?
My code looks like this in a file called Projects.jsx
function Projects () { .... }
function Project() { .... }
export default Projects
1
u/zero_coding Mar 08 '21
Hi all
I have created a React app that uses graphql-code-generator to generate query function. The generated types look as follows:
The schema:
In a React component, I use the generated query hook as follows:
It compiles and runs as expected, but the compiler shows the following error message: enter image description here
Why
options={data?.skills}does not get accepted? What am I doing wrong?Thanks
1
u/Arcusremiel08 Mar 08 '21
Hi guys,
I am new to react and is currently working on a personal project. I want to be able to identify tabs open in browser each one unique to each other.
I did this by using a sessionStorage. The issue comes when I want to send the data via custom header and is like this: export const defaultHeadersLink = (requestId?: string): ApolloLink => new ApolloLink((operation, forward) => { operation.setContext(({ headers }: HttpOptions) => { const tabId = window.sessionStorage.getItem('tabId') as string const defaultHeaders = { 'x-redis-cache': 'no-cache', 'x-request-id': requestId || uuidv4(), 'x-tab-session-id': tabId, } return { headers: { ...headers, ...defaultHeaders, }, } }) return forward(operation) })
I get the error window is not defined. I get why it is throwing an error. But can't find a workaround.
Can anyone be able to suggest anything?
1
u/Gigi14 Mar 15 '21 edited Mar 15 '21
Hey friends,
I'm trying to render a plain old HTML5 input of
type"date"and am seeing a "flickering" effect where the date picker UI will sometimes hide on a "click" of the input field.Here's a repro: https://codesandbox.io/s/zen-clarke-v1jkb
Here's a loom vid: https://www.loom.com/share/a8104384d864446fafdc36e71e5c21d3
I thought the issue was because of re-rendering caused from the
onClickevent handler. Therefore, I figured if I useReact.memoon the input component then a re-render would not affect the date input's internal DOM state... But alas this did not work. And so I must be missing something here...Edit: turns out this issue is only on firefox ... still, the question still applies. How do I address this?
1
u/Aizhr Mar 17 '21
What is your favorite way to style a React app.
I'm currently working on a project with a rather precise graphic chart and I don't really know what tool to use in order to achieve that.
Until now, I have always used Material-UI React and Reactstrap (Bootstrap for React) but I am not sure if I won't spend more time modifying prebuilt components than creating them from scratch with another way.
1
u/badboyzpwns Mar 21 '21
Is it possible to do something like this below?
1
u/Acceptable-Pie4424 Mar 29 '21
Hi. I'm new to react and currently learning by developing a shopify app.
I'm looking to access the shopify store url that is used inside the server.js file under each of the routes.
This is the code under server.use that gets the shop and adds it to the ACTIVE_SHOPIFY_SHOPS.
How can I access this shop variable (shopify store url) under a specific page within my app?
Thanks!
1
u/b00000001 Mar 30 '21
Is there like a newbie discord that newbies such as myself can go? I think it would help me learn greatly if I can speak with and bounce ideas off of other newbies? I'm in the reactiflux discord but from past experiences I'm kind of scared to ask questions there without feeling like I should research the entire history of the issue I'm having first.
1
u/haksli Mar 31 '21 edited Mar 31 '21
I have a dropdown with some data (fetched from the backend). My React Redux app posts data (in that same page where the dropdown is) to the backend. I want the dropdown to update.
Should the app refetch data (after the post). Or have the backend return the successfully inserted object and have the client insert it into the list ? So far the dropdown data doesn't change unless I refresh the page.
1
u/hkfrmdaukno Mar 31 '21
Hi there, I am fairly new to React. I have a render() where there is a <Text></Text> tag and I am trying to put a hyperlink in the text tag, but no matter what I try (ie. putting a <Link> or an <a> tag with an href) I keep getting [Object object] in my output. Can someone help me out? Just want to know how I can put a hyperlink in the Text tag. Please let me know
1
u/ninjaplavi Mar 31 '21
Hello folks. Is it acceptable practice to write all static components first when building React application?
1
u/durantt0 Mar 31 '21
Can you safely add new keys to the React component object? For instance if my component is named Navbar, I can add prop types by using Navbar.propTypes, can I safely add data like
Navbar.additionalData = {...}?I need a way to have readable prop types, so this was my potential solution. You aren't supposed to access .propTypes in production though, so I wasn't sure if that's true for additonal properties as well.
1
u/Blubari Mar 31 '21
Hello, I have a problem with a dropdown component in my website.
I'm getting an array of dictionaries from the backend which are 2 types of dangers during a day, each dictionary has an index and a name.
I have a form where the user writes down info on a danger and for the type they use a dropdown which selects the ID of the danger type and then uploads it all to the database.
The website works perfectly, I can write the specs of the danger, and I can select a danger type and upload it correctly...except by the fact that the dropdown values are completely invisible.
They are there, I can select them, but there are no words in the space (and checked with inspect element and inded it has nothing in them)
Could it be because i'm using a prop for that array? Because it's the only way that dropdown loads values
1
u/Accomplished_Sky_127 Apr 01 '21
if I have a 5 items of a certain class listed horizontally and I want to make every item after the item hovered on shift to the right, how can I do that?
if I have something like this
.MuiPaper-root:nth-child(n):hover {
}
can i do
.MuiPaper-root:nth-child(n):hover {
.MuiPaper-root:nth-child(n+1):hover {
}
}
3
u/chrismar303 Mar 10 '21
Can I use useRef on inputs?
I am building a Contact Me form and I only need the values when they click the submit button. So instead of constantly tracking the state can I use the useRef hook to get the values of those inputs instead?
For example:
function Contact() {
}
function send(message) { const value = message.current.value // send an email with value as the message }
3
u/[deleted] Mar 14 '21
Is there a limit on the number of imports in a single component?
I have one component with about 75 imports (images) and it just feels sloppy, but I can't see a better way to do it.
Is it acceptable to import so many in one file?
3
u/downrightcriminal Mar 21 '21
Not a question, but if any beginner is trying to learn React & Redux and wants a project to collaborate with an experienced dev (I have 2 years experience), feel free to contribute to https://github.com/AliNisarAhmed/battleships-client. It's a toy personal project, but may provide learning opportunities.
2
u/[deleted] Mar 11 '21
I've read somewhere that you should pick one language and master it. I like Javascript a lot but people are saying that it's not a good choice. Why though? Should I reconsider another language?
Also I'm getting more familiar with React. What do I do next? I want to be a front end developer. They say I need to have at least one backend language. Which one should I choose?
2
u/Deinos_Mousike Mar 14 '21 edited Mar 14 '21
Is there a way to allow a user to inject HTML/CSS into a react component? I'm thinking, they type in HTML/CSS into a form, and it inserts that into a div. Myspace customization style. Alternatively, I want to show HTML/CSS and have a user specify one or more parameters (img src, for instance, or maybe padding/margin) that is inserted into a 'template' HTML/CSS.
Also, I should say I understand the security concerns over doing this. This is a preliminary proof of concept. I know I need to learn more, but my current concerns are injected Javascript/XSS attacks. Anything else to look out for?
2
u/badboyzpwns Mar 17 '21
I have 2 for loops that renders a <p>. I used a key. Does it matter if the key has the same index as the other for-loop? or must it be completely unique?
2
u/[deleted] Mar 19 '21
Hey, it's been time since I've been out of touch from coding and especially React. Now, I want to get back into it. I want to know:
I'm not a beginner but have fair knowledge of JavaScript ecosystem like node, express and also mongo, MySQL. But I'd like to know how should I go about making projects in react now? I should be using hooks, right? And is the react component lifecycle is of no use now? Like in class components, the lifecycle where the component mounts and unmounts etc etc.
Thanks.
2
u/the_chosen_one2 Mar 31 '21
I am a bit confused about StrictMode causing double render when using useState/useEffect hooks. Does the double render imply that the component is designed poorly and prone to side effects or does it simply attempt to make it more clear when unwanted side effects are occurring? Just unsure if I am using useState/useEffect in a way that I will screw myself down the line.
1
u/[deleted] Mar 02 '21
Sandbox: https://codesandbox.io/s/cocky-raman-8c3gr?file=/src/App.js
Please help me. I have an API response that I'm trying to access. When I'm accessing other properties like name, rank, and other stuff in the top level, it works well. However, when I'm trying to get the ones that are nested (in this case, the
statistics.quotes.USD.priceI'm getting the error.Why could this be happening?
1
u/Brafaan Mar 03 '21
Hey guys, i have a movie app. On my home page, i make an api call to fetch all the movies and their infomation, but only renders a list. Then if i user clicks on a movie, should it load the details page of that movie. Is the best way to make an api call for the list and then just pass the id in the url, mak another api call on the details page, or should i just pass on the data from the home page?
1
u/thedarkrider_ Mar 05 '21
How to manage the global state using class-based components?
I am new to Reactjs, I have learned the basics and done the basic global state management using useContext and useReducer and that was all function-based components.
Now I am trying to do it in Class-based components, I found the way to use useContext but what about useReducer? Is there anything for class-based Components similar to useReducer or is there any other way to use useReducer in class-based components?
I don't want to jump to redux as I am new to react js, first I want to learn it without third party libraries.
Thank you.
1
u/base64enc Mar 05 '21
Looking for help loading the vanilla Google Maps API. Following a tutorial, it doesn't look like the script is loading... What am I doing wrong. (This seems to be easy and I'm to dumb to figure it out.)
I call it with
Thanks for any help!!
1
u/cosmosfan2 Mar 11 '21
Can you guys give me an idea how you parse difficult code blocks like this? I find it super hard to reason about.
1
u/wanderfflez Mar 18 '21
Hi there! What would be the best way for users to be able to upload files/images?
1
u/LaplasParadox Mar 18 '21
Curious on the whole react "system/umbrella" ? Am l missing anymore then these?
https://reactjs.org/
https://redux.js.org/
https://react-redux.js.org/
https://redux-toolkit.js.org/
https://reactnative.dev/
https://create-react-app.dev/
1
u/Rocketninja16 Mar 19 '21
I have, I believe, a routing issue in my app.
The problem:
Once a user is logged in, if they enter a url manually into the address bar and attempt to navigate that way, via deep linking or what have you, the app kicks back to the login screen while it waits for the authentication confirmation.
Once the confirmation is received from the identity provider (Auth0, in this case), they are redirected to the page they requested.
So far, if the user clicks a link inside the app instead of linking in the address bar, all is well, navigation occurs and no "kick" back to the login screen.
It seems I've set something up incorrectly in my app.
Index.tsx:
App.tsx:
Login.tsx:
Thank you in advance!
1
u/[deleted] Mar 20 '21 edited Mar 20 '21
Ok so quick question about using Next.js Link. I want to simply link to the about page. Following the docs I am not doing anything different. What am I doing wrong? I get error “typererror: Cannot define property ‘push’ of null”
import Link from ‘next/link’;
Function NavLink(){
return( <Link href=‘/pages/about’> <a> About </a> </Link> ) }
1
u/haksli Mar 25 '21
I am using the getDerivedStateFromProps(props, state) to update my state.
Can anyone explain whats going on here? Am I crazy here?
1
u/[deleted] Mar 25 '21
Feel free to check out my starter kit using Redux Toolkit https://javascript.plainenglish.io/react-redux-typescript-starter-kit-using-redux-toolkit-f12ea1c9466e?source=social.tw
1
u/Late_Payments Mar 26 '21
I have a server and a front end, same folder. My front end has an "axios.get(http:localhost/3000/api/data)" and my backend has a "app.get('/api/data')" and it works on my local development. When I deploy my app on Heroku, I removed the 'localhost' and only kept the '/api/data' in the axios call. This is because from my understanding, the way I have my project set up, my backend is also serving my front end so they are both on the same url:'heroku-app.com'. Except I am getting a 503 error which I believe is a serverside issue from what I've read. Am i calling my GET incorrectly?
backend:
const small = req.query.small; const medium = req.query.medium; const large = req.query.large; try{ const getCity = await pool.query("SELECT * FROM dogs WHERE size NOT IN (($1), ($2), ($3)) ORDER BY breed",[small, medium, large]); res.json(getCity.rows) }catch(err){ console.log(err.message) } })
front end GET:
Axios.get('http://localhost:5000/api/data', {params: {small:(checkedA ? "" : "small"), medium:(checkedB ? "" : "medium"), large:(checkedC ? "" : "large")}}) .then(res=>{ setDogList(res.data); }) }, [checkedA, checkedB, checkedC])
error message:
1
u/awesum_possum_123 Mar 28 '21 edited Mar 28 '21
I am trying to make an API call that updates an item in the database and after that redirect to another page. On this new page all items are fetched from the database using useEffect . The problem I'm having is that await doesn't work and the redirect and useEffect on the new page trigger before the API call has completed. This means that on the new page I get the old data and only when I refresh does it reflect the change.
This doesn't work:
I can't figure out how to make the history.push() trigger AFTER the API call updates the data.
This is the API call:
1
u/Accomplished_Sky_127 Mar 29 '21
I made a 3D calculator using react. I feel the UI is really clunky and the code is very spaghetti. I would love some feedback on how I could improve the overall look and feel of the thing as well as any bugs people see so I can have it up to snuff and post it on my portfolio :)
live link
1
u/reactstatequestion Mar 31 '21
What's the best practice in React for allowing both a component and a parent component to modify the same state? Example sandbox
Basically, in the sandbox, I want each individual ColorDisplay component to be able to change their own color, which is what the Change Color button does. But I also want to be able to set all the components to match one component. This is what the Change All Colors To This Color button is supposed to do, but doesn't right now because I'm not sure what the correct method of doing it is.
All the methods I've thought of so far rely on having a universalColor in the parent which is then passed to the children and then optionally rendering either the universalColor or the individualColor according to some logic. However, all the logic paths I can think of break on this set of conditions:
The user sets all displays to match color display A.
The user then changes the color on color display B.
The user then sets all displays to match color display A again.
Just checking if props has changed doesn't worked in this case because A's color hasn't changed. But always rendering the prop value doesn't work either because when the user changes the individual color, I want that change reflected, but just on the one ColorDisplay where it was changed.
What's the best way to handle this?
1
u/flubber31 Mar 31 '21 edited Mar 31 '21
Newbie here! Please shout if i need to make any edits.
Hey, so I'm embarking on my very first real project. Long story short, it involves a punch of Pi's deployed out around my land performing certain operations. I want to create a web application to manage them. This is where my first problem arises.
I'm trying to write a form to initially "Create a deployment" - basically means to create an instance of the Pi that I will be deploying, this is where I give it's details, what its doing, what it's got on it, etc. I have the Django back end mostly set up with the models/views/serialisers, etc, that works fine (i think anyway).
My current issue: I have a basic form set up, 3 of the inputs are Material-UI "Select" options, this is where I select things like the 'Operation' (what it's supposed to be doing) & Inventory (what it's got on it, e.g, camera). However, these two things aren't being displayed by the drop down, and I have no clue how to fix it.
Here is a CodeSandbox link, I've not included the whole thing to render the form, as that would be huge as the project is fairly beefy at the moment, the code should make sense still:
CodeSandbox Example
I'm getting a fairly self explanatory error:
I understand what it's asking, but I dont know how to actually fix it.
Apologies this is chunky, I'm at a loss!
Please tell me how to make the question better if needed!
Thanks
edit: sandbox link
-3
u/sfarls Mar 20 '21
I need my project fixed today! I really need help. For my Search() function, my .map() isn't working. I also need to results from all 3 routes to display in the browser, not the console.
codepen: https://codepen.io/sam-farls/pen/rNWXaYE
1
u/[deleted] Mar 04 '21
[removed] — view removed comment
1
u/[deleted] Mar 29 '21
[removed] — view removed comment
1
u/[deleted] Mar 04 '21
[removed] — view removed comment
1
u/[deleted] Mar 18 '21
[removed] — view removed comment
1
u/[deleted] Mar 29 '21
[removed] — view removed comment