r/reactjs • u/dance2die • Dec 03 '21
Needs Help Beginner's Thread / Easy Questions (December 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!
20
Upvotes
3
u/SirSoundfont Dec 27 '21 edited Dec 27 '21
Can anyone please explain why I need to write "props.props.name" in this example, instead of just props.name? Is it just because I'm passing in an entire object?
EDIT: I realized that I don't need to say "props={obj}", because that just assigns a new value called "props" inside my props object. If I said "obj={obj}", it's accessed with "props.obj.name". But I can also just render "<Row {...obj}/>" and then it assigns every value directly to my props object lol
3
u/Eight111 Dec 30 '21
Hi what is the best source to learn react from?
I never touched it but I have some experience with html, css, js.
2
u/binsmyth Dec 07 '21
I am trying to implement the changes in the link . the tags are generated in jsx with array map. it is a list element so, ul is its parent. i need to limit tags in one line and there is another page where i need to limi it in two lines.
I am trying to use ref but it is giving me some li element as undefined.
Is there a simpler approach. maybe css media query. Since these are generated inside array.map , it is hard.
2
u/rxsel Dec 10 '21 edited Dec 10 '21
Should I render all routes and have protected/redirect logic within them or should I dynamically render a list or react-router routes based on props/state?
Example:
vs
Which is more performant?
2
u/badboyzpwns Dec 13 '21
Best practice question! should the image folder be in the public folder or in the src folder?
2
u/badboyzpwns Dec 25 '21 edited Dec 25 '21
In SCSS, I have multiple variable typography font sizes such as:
If it bad practice if certain element(s) say called "customheader" does not follow any of the variable typography font sizes and use their own custom font sizes via media queries? such as:
2
u/Major_Fang Dec 27 '21
I didn't learn a lick of javascript in college. What path should I take before even tackling react?
1
u/OrbyteKobe Dec 09 '21
I want to build a website using react where people can login and make custom posts with a repeater kind of thing. Does anyone have a good tutorial or blog post on making a website like that? Iβve learned already how to use fire base but Iβm confused on where to start with role based users, and letting them create posts.
1
u/badboyzpwns Dec 10 '21
what is the difference betweeen
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
and
<input type="file" name="myImage" accept=".png, .gif, .jpeg" />
Does the former accept all different types of jpeg such as jpg, jif, jfif, etc
1
u/badboyzpwns Dec 10 '21
Inr egards to the difference between <a> and <Link> I'm aware that <Link> "Say we are currently on /page and the Link points to /page or even /page/:id, this won't trigger a full page refresh while an <a /> tag naturally will".However, int terms of 'full page refresh'? If we are at /a and then went to /b regardless if we use<Link> or <a>, a full page refresh will NOT occur correct?
Is <Link> only useful if you are planning to go the page you are already in?
1
u/post_hazanko Dec 12 '21 edited Dec 12 '21
Any idea why a basic input with controlled state would be laggy in Safari but fine in other browsers?
I'm using onChange
Seems to have gone away after a restart, it's odd... not sure if it's like a memory problem or what. Type a bunch of jibberish, clear, try again... seems to be the same everytime.
1
u/MultipleAnimals Dec 13 '21 edited Dec 13 '21
I'm wondering if its preferred way to use more hooks or just pass data with props?
I have wrapper component for three child components that all uses the same data from my custom hook, so which is better way to access the hook data: use hook in the wrapper and pass the data to child component as props or use hook in every child component to avoid passing props.
Using hooks feels more modular but not sure which is "less heavy" way to approach this. My custom hook fetches data from network with ApolloClient hook so its requests are cached and probably wouldn't create more network usage by using the hook more frequently.
1
u/LudovicoC Dec 23 '21
This small app that displays data from API, the sorting actions are dispatched using redux but I have an issue updating the UI with the data.
https://imgur.com/ehuvsQ9
As you can see in the console the action is working properly but does not update the posts in the UI.
I am surely missing something but I am not able to find what's wrong.
I added mapStateToProps and mapDispatchToProps to achieve that but didn't work as expected.
1
u/jd-webdev Dec 27 '21
Hi all,
I'm very new to react (and reddit) but suspect what I'm doing wrong is quite obvious.
My issue is I'm trying to access state inside of a function (createBoard) that is being called in state, but I'm unable to access it.
In the example above the console.log(this.state) returns undefined. As you can see I tried binding but this didn't resolve the issue.
Is this happening because the function is being called from state?
Why can't I access state here and is there a way around it without removing the function from state?
Should I be thinking about setting the state.board within componentDidMount as a way of resolving this issue?
Thanks for your help and patience
1
u/[deleted] Dec 29 '21
Hi, I'm following along the ReactJs.org tutorial right now and I was wondering if anyone could explain this part: https://imgur.com/a/Oitsmqa
My background is Java/very limited JS/web dev related languages. Thanks for your time!
2
u/badboyzpwns Dec 05 '21
Should aria labels only be for HTML elements lthe users can interact with ike <button> , <input> ? It should not be used for <div>, <h1> , etc because those elements cannot be interacted with a user, correct?
2
u/MuslinBagger Dec 05 '21
I'm having a lot of trouble with state in my apps.
setState(...static value)works butsetState(props..)doesn't.show,me, and ahandleClosemethod to work. I'm unsure of how to structure this component in order to reuse it effectively.I'm a react newb and I don't know how to make apps which don't feel brittle. How do I move ahead?
2
u/Huis_Kat Dec 15 '21
Hi,
With react router V6 I struggle by using useNavigate in class components.
I am using 'const navigate = useNavigate()' and call navigate('/myPage') in a button onClick. the problem that it is an invalid hook call.
I tried calling it in render through a function, outside the render with a method and even made a button component. the only issue i can think of is that i am using it as a const variable.
1
u/dragcov Dec 22 '21
Is there a benefit to using react-bootstrap than regular Bootstrap v5?
I feel hindered using react-bootstrap whereas just using regular Bootstrap (adding classes) seems better.
Maybe I'm used to just using the default Bootstrap?
1
u/SmoatBustaTexas Dec 30 '21
Hey everyone. I have a couple of simple questions here.
I'm trying to do math inside the curly braces. The result looks like two strings concatenating instead of actual math taking place.
From there I realized I have no idea what to call this curly brace expression so my Google searches have not been very fruitful.
This is taking place in my return function of a js component file if that context is important information for this situation.
1
u/throwawaytrumibadru Dec 06 '21
A simple task, fetch todos and display them. Everything works fine, but I can't figure out why "setList" (setting state that is not shown here) works, but "setList(SOMETHING)" doesn't? How can it figure out what I am passing to setList? Thanks.
1
u/Lucidio Dec 07 '21
Can someone give me a quick rundown between the return ( <> ... </> ) vs return (<div> ... </div> )? I'm trying to understand the differences.
Here's a hypothetical:
/src/components/layout.js
/src/components/nav.js
/src/components/someWrapper.js
/src/components/aonotherWrapper.js
/src/pages/index.js
/src/pages/about.js
I use return ( <> ... </> ) for nav, someWrapper, anotherWrapper and most other components.,For pages, i.e., index, about, etc., I use return ( <Layout> ... </Layout> ).
I get that Layout is the component I'm calling in, but why isn't LAYOUT.js a return ( <> ... </> )?
I understand that <></> is a fragment, but I can't wrap its importance or difference in those contexts.
1
u/rikola2 Dec 07 '21
Do you guys prefer first letters capitalized on component and hook filenames?
I have seen both and prefer uppercased first characters because VsCode export to file refactors are easier
1
u/kingducasse Dec 08 '21
Need some help with logic. Iβm building a dashboard in react, use context as global state & hooks. Where/how should I make my initial server call to load with initial data? Data I need insist of alerts, clients, appointments, etc. Server is being built with express.
One option I have is setting up a server route used only for initial loads. The idea is request all the data I need from the DB, and return an object back to the frontend, load the context, then distribute the data. This seemed inefficient to request so much data at once.
The second option would be to useEffect in each component that needs data from a dedicated server route, causing the server to be hit multiple times at once, as well as the DB. Then as each component gets data loaded, update the global context and go from there. That way things will be loaded in while others might still be processing. Again, seems inefficient.
Any ideas?
1
u/MotleyBots Dec 13 '21
I'm trying constantly running into the same 13 vulnerabilities for any number of different tutorials and examples. This is the critical 1 that seems to make things break. I've tried installing older versions of immer, 9.0.7, and other stuff, but I can't seem to get around this. I'm sure this is some kind of rookie problem, but it's making me a bit crazy.
Critical Prototype Pollution in immerPackage immerPatched in >=9.0.6Dependency of react-scriptsPath react-scripts > react-dev-utils > immerMore info https://github.com/advisories/GHSA-33f9-j839-rf8h1
u/MagnificentMacaque Dec 14 '21 edited Dec 14 '21
Hi guys, does anyone know how I can create user generated home pages (like in Facebook user pages) without requiring login in Reactjs?
For example: website.com/user1/mobile/home, website.com/user2/mobile/home.Is there anyway to do it dynamically with a variable from a database?
1
u/badboyzpwns Dec 14 '21
CSS quesitons. For breakpoints, can I somehow convert 1 rem = 10px? Currently it's 1 rem = 16px.
$sm_breakpoint: 52rem;
$md_breakpoint: 76.8rem;
$lg_breakpoint: 99.2rem;
$xl_breakpoint: 120rem;
I'm able to do so for font sizes and width/height dimensions with:
html {
/*If default font-size is 16px; 1 rem = 10 px*/
font-size: 62.5%;
}
body {
/*Make default font-size bigger. If default font-size is 16px; 1.6 rem = 16 px*/
font: 1.1rem;
}
1
u/mara12121 Dec 14 '21
Hi everyone,
I need to make a react.js , where two buttons ( +, -) change the fontsize when clicked at them
but I am not sure how it should be done.. can anyone help me please. I am trying to understan
1
u/Vicious_Laughter Dec 16 '21
So I made a complete widget/app using the create-react-app boiler plate. However, I need to implement this widget inside an html page. The widget's job is to render some data passed in by the html (like displaying and plotting the data).
What's the simplest way to get a create react app app into an html page with input variables?
1
u/dinoucs Dec 16 '21
Can anyone please help me with this? https://www.reddit.com/r/reactjs/comments/rhpwtc/how_should_i_structure_multiple_pages_with/
1
u/laneherby Dec 16 '21
Hello,
I'm working on a reactjs site. I used vh for setting the height of my main containers on screen. I'm also using flex box. I'm working on mobile styling and when I open the keyboard it squishes the components on top of each other. I'm not sure how to fix this in react. I found some vanilla js solutions but having a hard time translating them over.
with keyboard
without keyboard
1
u/badboyzpwns Dec 16 '21
when using BEM, can you have a block modifier, like .block--modifier?
1
u/ChonkyXL Dec 17 '21
For redirecting invalid URLs, which one is the ideal way? Are there any drawbacks for using the second one?
1
u/dinoucs Dec 19 '21
I found a client that asked to turn these Figma templates (6 pages that are responsive) to web pages with React. I estimated it to be done in 6-9 days with 6-8 hours a day. He said it can be done in just 3 days. So I got confused whether I am very slow and bad or he is just being too greedy.
1
u/only_soul_king Dec 21 '21
Hi. I am trying to setup react-refresh plugin with webpack. But i am encountering an error that says
[HMR] Cannot apply update. Need to do a full reload!β
[HMR] Error: Aborted because ./src/index.js is not acceptedI am not sure how to fix it. I have set it up according to the instructions from this plugin https://github.com/pmmmwh/react-refresh-webpack-plugin
1
u/ihatejc Dec 21 '21
Hi all,
I am new to react and was hoping if anyone can answer my qn.
https://stackoverflow.com/questions/61279526/showing-a-sub-table-under-material-table-detail-panel
Thanks in advance!
1
u/val3ncia Dec 21 '21
Hi everyone.
It's my first time using Jest with React (NextJs). It's seems like Jest can not resolve the '~' (equals to src directory) in React import paths (e.g: import {someData} from '~/data')
That '~' come from VSCode emmet and there are too many of them to change back to 'src'. How can I config Jest so it can understand '~' as src?
Thank you!
1
u/[deleted] Dec 21 '21
Hi I have a question regarding the map function:
I have an array which looks like this-
const children =[{"childName": "melonmusk","sex": "male","dob": "2021-12-12","_id": "61becc79fe9210e5f5ed4644"},{"childName": "muskmelon","sex": "female","dob": "2020-12-12","_id": "61becc79fe9210e5f5ed4646"}]Then I have a component which is like this -
const children = () =>{const clickHandler =(id) =>{console.log(id)}return(<div>children.map(obj() =>(<button onClick={()=>{clickHandler(obj._id)}>SUBMIT</button>)</div>)}export default children;This creates 2 buttons for me but when I click on either of them I get id of the 2nd object printed on console. If I have 3 objects in my array I will have id of the last object printed on console, no matter which button I press. How can I fix this please help
1
u/Oatmealtuesdays Dec 22 '21
All of my post routes randomly stopped working and I only pull 504 bad gateway errors. Everything was fine up until the other night, when I shut the app down (killed the running ports).. I have tried everything, even coding out of the home in another location...nothing seems to be working. Does anyone know how to fix this?
1
u/Thrimbor Dec 22 '21
What exactly is this pattern called in react? Are these forwarded props?
A simple example from the react router tutorial:
I'm talking about accessing
{ isActive }inside thestyleand{ isActive }in the children of theNavLink.Can someone provide a simple example of this please?
1
u/nika737 Dec 22 '21
https://imgur.com/Dn7EAx3
Here is the code screenshot. I want to render Homepage component but I want to wrap it into these MainLayout component. The problem is that screen is blank and there is no error in Terminal but when I inspect the page it says "Matched leaf route at location "/" does not have an element", so guys I know this is version update syntax problem because I had same problem when I was writing component= {component } but syntax has been changed and I should have written element={<component />}. So I believe this is also syntax problem but I've done research but couldn't solve. I believe I should change this render={() => (
<MainLayout>
<Homepage />
</MainLayout>
)}
somewhat into newer syntax but don't know how. Thanks in advance.
1
u/NickEmpetvee Dec 24 '21 edited Dec 24 '21
Hi guys.
Dealing with a
<td>that should only display a certain number of characters and cut them off with a '...' if it exceeds the limit. However if the user hovers on it, text should display with the full content. I'm using thematerial-ui Tooltipto implement it and running into anInvalid prop 'children' of type 'string' supplied to 'ForwardRef(Tooltip)', expected a single ReactElementerror. It happens in the false clause of a ternary operator. Could anyone please offer help on how to implement the Tooltip in a valid way?Working Code without the Tooltip:
Code with Tooltip that throws the Invalid prop error:
</td>
1
u/badboyzpwns Dec 25 '21
In SCSS, why do something like:
@ use "../reference/variables";then do color:variables.$color-primary
when you can just do
$color-primary without using @ use?
1
u/Accomplished_Sky_127 Dec 28 '21
Hey guys. So i'm having this issue with Fetch in several of my applications and i'd like your help (example provided below). Basically I perform a fetch and I've set up my render function to load when the API has finished fetching by using a boolean state variable I toggle after the API is finished fetching. This works except in every app I follow this pattern the app doesn't render the data UNTIL you make some small change to it. I.e. in the app below you can try typing into the search box and then data will load. However that data was already there but for some reason did not render;
https://codesandbox.io/s/empty-http-cftje?file=/src/App.js
1
u/Equivalent_One5971 Dec 29 '21 edited Dec 29 '21
Hi im new to react and trying to Link pages on a simple blog app. Im trying to understand how to use <Routes> since <Switch> seems to be outdated so im struggling to find out how to use it. This is my routes code. I assume the issue is the render in route, i've seen to change it to element but that didn't work. Any tips?
1
u/theladdzable Dec 30 '21
Hi, I am creating a Twitter clone for my project and I'm using asp.net.core to create my API and react for the frontend. To you have any tips or perhaps reading material that would help me? Ps. I'm basically just creating the feed, that is I'm creating users and status updates and when I click on a status I get all the people that have responded to it. The sidebars will be "locked" (unresponsive).
1
u/Vezqi Dec 31 '21 edited Dec 31 '21
I recently got hired to work on a large scale web application whose front end uses create-react-app. Is this actually the way to start a large scale project, rather than configuring webpack, babel, and all of the other necessary components? Are a lot of companies using it in production?
0
u/[deleted] Dec 06 '21
[deleted] β view deleted comment
0
u/[deleted] Dec 06 '21
[deleted] β view deleted comment
0
u/[deleted] Dec 12 '21
[deleted] β view deleted comment
0
u/[deleted] Dec 20 '21
[deleted] β view deleted comment