r/reactjs • u/dance2die • Sep 01 '19
Beginner's Thread / Easy Questions (September 2019)
Previous two threads - August 2019 and July 2019.
Got questions about React or anything else in its ecosystem? Stuck making progress on your app? Ask away! Weβre a friendly bunch.
No question is too simple. π€
π Want Help with your Code? π
- Improve your chances by putting a minimal example to either JSFiddle or Code Sandbox. Describe what you want it to do, and things you've tried. Don't just post big blocks of code!
- Pay it forward! Answer questions even if there is already an answer - multiple perspectives can be very helpful to beginners. Also there's no quicker way to learn than being wrong on the Internet.
Have a question regarding code / repository organization?
It's most likely answered within this tweet.
New to React?
Check out the sub's sidebar!
π Here are great, free resources! π
- Create React App
- Read the official Getting Started page on the docs.
- /u/acemarke's suggested resources for learning React
- Kent Dodd's Egghead.io course
- Tyler McGinnis' 2018 Guide
- Codecademy's React courses
- Scrimba's React Course
- Robin Wieruch's Road to React
Any ideas/suggestions to improve this thread - feel free to comment here!
Finally, an ongoing thank you to all who post questions and those who answer them. We're a growing community and helping each other only strengthens it!
36
Upvotes
3
u/chekkanz Sep 26 '19
Should a function that returns a component itself always be a react component? If so, is there any apparent benefit of choosing one over the other?
Or...
2
u/[deleted] Sep 01 '19 edited Sep 01 '19
Basically I am trying to build a solar system simulation, I have created all of the orbit animations etc. and I've added the components inside a ScrollView as shown below:
For some reason the scroll view focuses on the last element which in this case is the sun <Planet/>and it when is use pinch gesture to zoom in and out it only does it in relation to that element making it impossible to zoom in to other <Planet/>elements.
I've been looking for a solution for days, one that I came up with is maybe making the scroll view focus on a different element when I tap it, but whatever I tried did not work. Thanks in advance.
2
u/CodeLight Sep 04 '19
Suppose I'm building a To-Do List, and I have a stateful Form component that keeps track of an input field's value. Upon submitting the form, I would call some method passed to my Form component as props named addToDoItem. I would then like to clear the input's field value, but only if the method addToDoItem was successful.
If the actual logic of writing to the database is found in a Parent Component, what is the best way to tell my Form Component that the To-Do item has been successfully written to the database?
I'm currently returning a Promise from the method that handles writing to the database, and only clearing the input field when it resolves like so:
Is there a better approach, such as passing some 'success' prop to the Form Component, or handling the business logic directly in the Form Component?
2
u/fanumber1troll Sep 29 '19
Is it normal to have a bunch of if statements in the useEffect hook? I don't understand how you can have a "one size fits all" for when your component renders, where you'd always want the exact useEffect ran over and over. If I have to use multiple if statements, should I split my use effects into multiple functions?
For a specific example, I have a popover component that will show a tool tip when hovered over, but then when you click it on it will trigger an api request and a window with a graph will pop up. If I don't have an if statement (if (open)), then my API request will fire when a user hovers over the pop up text, and I don't want that.
2
u/WhiteKnightC Sep 30 '19
I saw on the React tutorial that you can dinamically update a state using [var]. (Every [var] is different and doesn't replace others)
Is there anyway to do the same in a object state?
I tried, myObj: {[var]:value} but they replace the whole object. (Only one value saved)
2
u/load_up_on_hummus Sep 19 '19 edited Sep 19 '19
Can someone give me a simple explanation of why we would make API calls in
componentDidMount()to change the state after a component has already mounted? Why aren't we encouraged to retrieve data from API's before the initial mounting? Is this just for page load optimization, or is there a better reason?1
u/hurrdurrderp42 Sep 03 '19
I'm having trouble deploying my app to github pages.
App is made using create-react-app, i followed these steps https://reactgo.com/deploy-react-app-github-pagesMy source is set to master branch, because i didn't get gh-pages branch for some reason.
It's supposed to be deployed here https://red4211.github.io/react-twitch-app/, but it just shows README
I got some errors in npm while doing this - https://imgur.com/gHAIVQG
1
u/Dfree35 Sep 05 '19 edited Sep 05 '19
Figured it out here but not sure if there is a cleaner way.
Not sure the best way to phrase this question but can I have a mouse event trigger a component (I think that is what it is called)?
To give you an idea of what I am trying to do. I want to have some text that says "Share" and when it is hovered it changes into social media icons.
So I am trying to do this, it is a skeleton of the code:
It does not appear to work but not sure if this is possible or not.
1
u/Oipotty Sep 06 '19 edited Sep 06 '19
I'm using react-virtualized and I want to use exclusively functional components.
I call renderRow and the library seems to automatically pass certain properties into rederRow function (index, key, style, parent). But now I want to access the TestComponent props in the renderRow, is there a way to do that? I know I can do it in a class component by defining renderRow in the class
1
u/RedditAcctsInLrgAmts Sep 14 '19
How can I prevent a body scroll from occurring when the mouse is over a react component? I am handling the synthetic event within the component, and the desired action is taking place, but neither e.preventDefault nor e.stopPropagation actually stop the body from scrolling while the mouse is over the component. None of the articles or github discussions I have found had a solution I could successfully implement.
1
u/liohsif_nomlas Sep 17 '19
Hi, I am trying to save states in components after clicking the browser refresh or back button. It seems the two most talked about approaches are localstorage and sessionStorage. I also read that they are not very secure. Is it really bad to use either of them? and if so is there a better alternative?
1
u/guitnut Sep 17 '19
Hi, I'm trying to pass data to a component from state. The said component opens on a new tab with React router to allow the user to print a PDF of passed data but the data is undefined. I think I know what the problem is: the component is being rendered before the data is being set with setState.
How do I make the component render with the updated data?
onHandlePrint = (pdf) => {this.setState({pdf}, () => {console.log(this.state.pdf)})}<Routepath="/pdf"render={() => (<PDFDocument data={this.state.pdf} />)}/>A simpler version of what I want to do but this works. Not sure why it works but I think because the component renders on the same page.
https://codesandbox.io/embed/gifted-varahamihira-o8edu?fontsize=14
GitHub repo
https://github.com/christocarr/sibi-activity-search
1
u/Nahbichco Sep 18 '19
Hey guys, I am really struggling with using .map(). I understand it on a really base level that is used in all the examples I can find online, but I'm trying to map API data and I just cant figure out how it all works when I'm not trying to multiply an array of numbers by 2.
I have a massive array of data from the Google books API that Im trying to push into jsx (so for instance, I want to pull the book title so if I was using a for loop Id want to pull items[i].volumeinfo.title into <h2> tags) but I'm supposed to use map instead of a for loop and I just dont understand how it works. I am under the impression I wouldnt be using [i], but then am I grabbing the titles by just writing items.volumeinfo.title? And how do I start the map? I currently have
data.map(??? => { Return (<h2>{items.volumeinfo.title}<h2>) }
But A, I think I'm doing something wrong there and B, Im not sure what the parameter thing needs to be for the function where I have the ???. I've tried a couple different things (data, items...) But none of it is right and I can't figure out what is. Thanks for any help in advance.
1
u/kennerc Sep 21 '19
Hy, sorry if it's against the rule, I'm trying to learn react, and I'm trying to get a random number, however it always retunr Undefined on the Alert, I've tried a few variations of setstate, but nothing works, I know it's something really silly, bellow the part of the code:
export default class App extends React.Component {_onPressButton() {function Random(props) {var maxNumber = 20;var randomNumber = Math.floor((Math.random() * maxNumber) + 1);return <div>{randomNumber}</div>;}Alert.alert("Result: " + this.randomNumber);}Everything else is working.
1
u/hurrdurrderp42 Sep 26 '19
What's the proper syntax for
transform:rotateinline styles?1
u/FickleFred Sep 27 '19
Where is the proper place to call setState when you are processing data and setting it as the initial state?
So I have a component that is passed a data prop. Within that component, the first thing I want to do is grab that prop.data, run some processing on it to restructure it and then set it as the initial state. At the moment I am calling this from within componentDidMount but I wasn't sure if this is the correct place to do it since I'm not calling an API or running any asynchronous functions. I know you are supposed to keep your render method pure so I wouldn't execute it there. Is there a better place than componentDidMount to execute it? Can that be done in the constructor?
Below is the example:
1
u/spdz Sep 29 '19
Hey! A friend of mine is doing her first react project and she is having difficulties, I thought about looking on reddit then I found this thread.
Basically she is developing a Itβs a movie search using OMdb api(I guess). She made a search component and a movie component. The search works, but she canβt get the information from the movie select on the search to the movie component.
Any suggestions?
1
u/epitaphb Oct 01 '19
I deployed my first project made with create-react-app from my GitHub to Netlify, and on the browser console on every page (even in directories that have nothing to do with React), I get this warning:
content.bundle.js:22609 Warning: Accessing createClass via the main React package is deprecated, and will be removed in React v16.0. Use a plain JavaScript class instead. If you're not yet ready to migrate, create-react-class v15.* is available on npm as a temporary, drop-in replacement.I'm still new to React, so I have no idea what is happening behind the scenes to be causing this. When I search for "createClass" in VSCode, the only place it comes up is in a .map file in the build static folder, which is minified. As far as I know everything is up to date, so I'm at a loss as to what to do to resolve this. It doesn't seem to be causing any issues, but I'm going to be applying for junior positions soon, and I don't want the warning to be showing up in the console if anyone's checking, especially since it's everywhere in my portfolio.
1
u/majky358 Oct 01 '19
With previous experience with Angular, NodeJs I need to get into React in 2 weeks? Any suggestions? Will be the official guide and for example udemy courses enough to start with ?
3
u/castane Sep 06 '19
I seem to run into this issue a lot. Say you have an external API that might have a param that you need to check for:
When polling the API, you might have
data.customer.namewithout discount. In my code, I check like so:If
discountdoesn't exist, then it'll throw an error while checking for thecodeparam because discount doesn't exist. So I end up with:Which seems really verbose. Is there a better way to do this in the
ifstatement?1
u/epitaphb Sep 15 '19
I'm starting to build my first React project, and I want to make sure I understand the idea of inheritance vs composition. From my understanding, inheritance would be like having a BlogPost with a Like method, and BlogPostComment would extend BlogPost to have access to the Like method. And composition would be having Like be its own component, and both BlogPost and BlogPostComment use it. Is that right?
2
u/KRTac Sep 05 '19
I'm having trouble with `useEffect` and `renderToString`. Here's the code:
When run with node and express, I only get the `render` log on the server after requesting the page. When the page loads on the client, both `render` and `useEffect` logs are present.
Don't effects run on the server?
2
u/argiebrah Sep 06 '19
Are there any tutorials on setting up a react app with express and SQL with an ORM bundled up in typescript? I know it is very specific but I wanted to learn Typescript and scaffold it together
2
u/Reasonable_Space Sep 09 '19
Quick question: Is there any difference in calling async functions versus normal functions? I'm calling an async function:
using a button (onPress={this.reload}). However, some stuff, even when changed to a simple alert method that alerts a string, did not work as intended.
2
u/SavingsAssociate Sep 10 '19
Hi all! I have a question regarding
styled-components.In a component such as this (pseudocode):
I am confused if I should make every single thing a styled component, like this
OR if I should make the parent div a styled component and then use nested selectors and and classes to target the child elements, like this:
Is there a wrong and a right way to do this?
2
u/[deleted] Sep 11 '19
I've got a fixed header with a row of links that need to scroll to their respective section on the page when clicked. It seems really simple in vanilla javascript but I'm not 100% how to do this in react. It's a single page but the individual sections of the page and the header are pretty far apart in terms of their dom tree location.
I'm also using redux and so far have had success just adding a the ref to each section into redux's state and then just scrolling to it from there. But I was told to keep the state serializable so storing the actual ref wouldn't work. Next I tried just calling getBoundingClientRect().top on the ref and storing just that in the state with some success. I can reference it later and scroll to that value, but this value changes without re-rendering and can eventually become de-synced so that the links will start scrolling to the wrong places.
Is there an easy way to do this?
2
u/[deleted] Sep 17 '19
Started a React app in 2017 and finished in 2018. I'm getting ready to start another. Since then, Hooks and Context have become prevalent and something I need to understand better.
In addition to working on a React web app, I'm also going to build a React Native mobile app. This will also be my first React Native project.
So my question is: how I should structure my project while being able to reuse as much as possible? I think this would be limited to hooks, contexts, and the Express BE. Components and CSS would be too different to reuse between React and React Native, I'd think. The end goal too is to use Docker and K8S... another first on my part. The use of Docker and K8S might affect how the project should be structure as well.
This is the structure I was thinking, but wanted some feedback:
app-rootmobile-clientnode_modules/src/components/screens/App.jspackage.jsonserver/node_modules/models/routes/index.jspackage.jsonshared/contexts/hooks/web-clientnode_modules/src/App.jsindex.htmlpackage.json2
u/argiebrah Sep 19 '19 edited Sep 20 '19
EDIT: Solved (see answer on inner comment)! I am sending data to a database from react using hooks and axios and the problem is that it sends all data while i type. What could be the problem here?
And the database looks like this
2
u/Money_Macaroon Sep 22 '19 edited Sep 22 '19
Hey, so I'm just starting to learn hooks, and am running into some difficulties grokking how useEffect is supposed to be used. The array of objects in my state that I'm passing to useEffect as a dependency array seems to be causing endless rerenders, and I'm not sure why. Code outlined below:
function App() {const [events, setEvents] = useState([]);async function fetchData() {const res = await fetchEvents()setEvents(res)}useEffect(() => {fetchData()}, [JSON.stringify(events)]);return (<Calendar events={events}/>);}export default App;2
u/vnlegend Sep 24 '19
I've seen this a lot but when can you use
this.functionNamevs justfunctionName? I know that arrow functions bind this and people often use it with this.functionName, however functionName seems to work just fine in some places. Should you always use arrow functions for class methods?2
u/statsuya Sep 28 '19
It is possible to replace an ASP.NET-Web Forms app with React piece by piece? The Web Form parts would need to work in parallel with the parts replaced with React. So I would need the user to be able to go from viewing a page completely built with React and navigate to other pages still in Web Forms.
2
u/ldin019 Sep 29 '19
How can I use
renderItemwith nested JSON data? The more specific question and code can be found on stack overflow. Please help. I've been stuck in here for ages. Any help with some actual code will be much appreciated.https://stackoverflow.com/questions/58091457/react-how-to-render-nested-object-with-renderitem
Many thanks in advance.
2
u/shoegazefan Sep 29 '19
Would anyone be willing to look at my first react app and provide some constructive criticism? I feel like I made mistakes all over.
https://mindfullnote.herokuapp.com
https://github.com/eamrhein/MindfulNote
1
u/wirbolwabol Sep 03 '19
Wanting to learn ReactJS and started off with Kent Dodds course but I'm finding it frustrating in that he zooms through all of the stuff, and constantly revising the code so much that I'm overwhelmed with all of the stuff that he just showed...am I the only one to find these difficult to digest? I'm at the 5th video and they are all the same in the difficult to follow respect. Should I look at other courses?
1
u/SuddenFlame Sep 03 '19 edited Sep 03 '19
Hi, React newbie here!
I was wondering if there's there any difference / preference between installing node via homebrew or the installer (for dev purposes)?
Also, any penalty for a beginner using yarn over NPM (in terms of early tutorials etc) - the two seem fairly interchangeable in most cases so was considering going with yarn, but would appreciate thoughts.
1
u/ICNRWDII Sep 03 '19
Did you just use local storage as a database when you were just starting out? My current idea I could get away with just using local storage, although people would be really upset when they clear their history and loose the information. Is there some easy way, or a site that lets you store information more permentantly? Or do I have to wait until I've learned backend?
1
u/Niesyto Sep 03 '19
Question for job recruiters. When you get a resume for a frontend Dev do you pay attention to the way it looks? I always preferred simple resumes, one font type, no colors, no lines, no lines etc. Is this the reason I don't get too many replies?
1
u/[deleted] Sep 03 '19
I am trying to implement a filter option with checkboxes to a table with data. I am using Material UI react. How do I accomplish this? What's the approach in order to start building this. This is a link to what I have so far: https://codesandbox.io/s/table-w-filter-options-mui-gxbmx
1
u/jonnywaffles34 Sep 03 '19
Hey guys, question about a portfolio site. So I have been slowly making progress on a site (using create-react-app) that shows my work, mostly react apps from a udemy course and would like to know how to use React Router when I am routing to these other projects. As of right now i just have the bundles in different S3 buckets and just use basic hrefs to get to there. I have a basic understanding of react router as the course I was taking was touching on it but it covers it in the sense of different pages within the same project. Not different projects that can be navigated to from a parent start page. Currently the only "deployed" apps on the portfolio site are Expensify app and Indecision app (2 react apps from the udemy course). My best guess is to import the bundles from each of the projects and create a route to them but any insight would be very helpful. I hope this makes sense.
here is the portfolio page
http://jonathan-guzman.s3-website-us-east-1.amazonaws.com/
1
u/tubehacker Sep 03 '19
CSSTransition from react-transition-group won't persist
https://codesandbox.io/s/intelligent-pond-590jm?fontsize=14
Hi, I'm having a small problem where the red box won't stay elongated while value is set to true in state. The box grows but then it just shrinks back up.
I tried looking at the documentation but as far as I could tell the transition happens and should wait for the value to change to false before initiating the exit transition. There must be something I left out that persists the transition until the value is changed to false but I don't understand what it is.
1
u/SuddenFlame Sep 04 '19 edited Sep 04 '19
I might be overcomplicating things here, but would appreciate your help.
If I wanted to code up a page where there's a lot of "static" content, and some interactivity... like this: https://www.docusign.com/#
What would be the typical or cleanest way to do that?
Is everything a component? Could someone point me in the direction the source for a similar page? Or give me a quick overview of how you'd code it up (as in, what would be the type of the various blocks of content, where is the text specified, etc)
You've probably realised that I'm a "loads of pure HTML with a bit of jQuery" refugee :)
1
u/[deleted] Sep 04 '19
A react-spring question.
Essentially, I want to use react-spring to animate mounting/unmounting of little alerts on form submission, all with the same animation.
Initially, I set out to use useTransition for this. I tried passing an object as the
itemargument to the transition object's.map()method. I figured I could access a variety of that object's keys with true/false values for a variety of transitions. However, that doesn't seem to work.Currently, I'm calling
useTransition()repeatedly, for as many transitions as I need, so I end up with a bunch of transition instances that are all doing essentially the same thing. This works but I have to believe there is a less repetitive way of doing it.Here's a paired down, dummy version on codesandbox.
Thanks in advance!
1
u/NickEmpetvee Sep 05 '19
Don't laugh... but I'm using the below code to control the inputs of a password reset dialog. It does some standard stuff like make sure that the new password / verify password fields match, etc. and prints helper text if one of the entries needs correction.
It works functionally but I've heard that useReducer would make it smoother. I'm having some trouble understanding how the below handleChange could know about the action to pass into the reducer. I'm also trying to get my head around useReducer in general since I've never used redux, only contexts.
Thoughts / links appreciated.
1
u/Morters Sep 08 '19
Question about the use of Material UI.
I try to change an Avatar background color and I am trying to use CSS with 'background-color' attribute, but it doesn't change the gray color of it. It does, however, change spacing so the CSS file does work, but only the color is the issue.
Any idea on what should I do?
Thanks!
1
u/whatisaname2 Sep 08 '19
I have a react app connected to mongodb, and am currently able update the list of products in the db. I want this to function as an admin-only page and then have a static website generated from the product list when the admin decides to go live with the changes. Is it possible to generate a static html page with a react app?
1
u/Oipotty Sep 09 '19 edited Sep 09 '19
Hey all, another question as I switch to using exclusively functional components.
In the below code, I have a render function. What I want to access the rendered row that the user hovers over in the parent function (Test Component). What is the proper way to do this? Would I be looking to use Context or Redux or is there a more straightforward approach? In a class based component, this would be pretty trivial since my render function would be inside the class.
1
u/argiebrah Sep 09 '19
Hello Guys, I am making a project with react, next.js and typescript. I have some trouble with static images, as of today I tryed serving my images like the next.js docs, where it say to place my images like this
<img src="/static/logo.svg" />This didn't worked, so digging the file path leads me to this working:
<img src="/_next/static/logo.svg" />Will there be anydrawbacks using this? What will happen for example, if I push this code to production?
What is the correct approach?
1
u/liohsif_nomlas Sep 10 '19 edited Sep 10 '19
Hi, I have a question in regards to react router parameters and this.props.history.push that you can get access to from withRouter. My understanding is with react router paramters you might have a path like this:
/:id
where the id will be passed to the designated component and be accessed there through match.params. My question is if we are passing something like an id to be used in another page, what is the difference with using react router parameters and using withRouter's this.props.history.push as you can push an object containing the path info, and information such as the id to the next page with this.props.history.push. Any advice would be much appreciated.
edit: I think I got my answer, it seems the react router params and something like <Link/> or this.props.history.push should be used together. I believe this article will be helpful for others as well https://tylermcginnis.com/react-router-pass-props-to-link/ If I am still missing anything or if my understanding is still incorrect, please let me know. Thanks.
1
u/Apollo989 Sep 10 '19
So I'm having a bit of trouble on my app. It's almost finished front and back, but one thing is holding me back. Does anyone have any examples or advice for making collapsible components? Like, I have a series of "cards" I made and I want users to be able to expand them to get more information, but I'm having issues getting started on this part.
Thanks!
1
u/P-Lumumba Sep 10 '19
Material UI, <Textfield> not working when using value
Could someone have a look at this sandbox and explain me why it all works perfect when I use <Textfield defaultValue={value}>, but not when i use <Textfield value={value}>
The value is set in the state for both options, but when I use value, the <TextField> never gets updated with that new value...
I might be bald, but I'm pulling my hair out none the less...
1
u/[deleted] Sep 10 '19
Hello friendly ReactJS Reddit,
I am attempting to build a very simple FieldArray (Redux-Form required) portion within my React form and I essentially need it almost identical to the documentation (https://redux-form.com/8.2.2/examples/fieldarrays/) in terms of function but with two changes:
I have been playing around with many methods and have been getting stuck at how to initialize a single field (first element) as well as calling my renderMember function (for a new element) from outside the render.
And this sandbox is exactly what I need (Starts off with a first empty field, and add button remains on the bottom) but I cannot use Formik (https://codesandbox.io/embed/formik-fieldarray-materialui-f7rkz)
If I could get any help that would be awesome. Thanks once again.
1
u/workkkkkk Sep 10 '19
What are the pros/cons of server side rendering? What are some things to consider when deciding whether a project needs to use ssr or not?
1
u/friedseig Sep 11 '19
I hope this question is still part of the sub. I'm planning to buy Microsoft Surface Go 4gb Ram version. Is this still good for react development?
1
u/[deleted] Sep 11 '19
Hi everyone,
I am learning react-redux and trying to implement my async communication using sagas.
I have written a simple example for me to learn good practice (this code just queries and updates the JIRA REST API)
actions.js
saga.js
reducer.js
Everything works. However I want to keep it clean going forward:
Where should I call fetchIssue after update? Directly in the saga? From the actions?
Should I use the saga to do object deconstruction or should I do this in the reducer? For example _.get(props,'issue.fields.summary','')?
If I catch an error with the REST client, should I handle it inside the saga or elsewhere?
Thanks!
1
u/javascript_dev Sep 11 '19
Using the NOT operator is shifting the value back super fast (true false, or false true), effectively sticking the checkbox on false or true unless I get lucky. I think the current pattern runs into a race condition against the render cycle. How do you guys fix this issue?
1
u/hurrdurrderp42 Sep 12 '19
Is typechecking every component with proptypes a good practice?
Also can you recommend me a tool to tidy my code? I use sublime text 3.
1
u/argiebrah Sep 12 '19
How to transform this stateless component into class bassed?
const Dashboard = ({ logout, session }) => (to this?
class Dashboard extends React.Component {Is it a good idea to use only redux for important states like user authentication?
because I am using ant design and it has state for dark mode and white mode.
1
u/ajaxknight Sep 12 '19
I have a question about react-router implementation and nested routes.
How would I structure my code in the following scenario:
Site layout:
--App
----home component=home
----samples component=samples
------samples/1 component=samples1
------samples/2 component=samples2
Currently in App.js I am have the Router and Routes for /home and /samples
App.js
Route path=/home component=home
Route exact path=/samples component=samples
and in the samples component I have Routes for samples1 and samples2
Samples.js
Route path=/samples/samples1 component=samples1
Route path=/samples/samples2 component=samples2
but I can't get samples1 or 2 to render without rendering the samples component also
Am I supposed to declare all routes in App.js or am I missing something?
1
u/mercfh85 Sep 13 '19
Curious if it's worth re-learning a bunch of javascript to learn react. Im not a developer but have a CS degree (Im an automation engineer at a company that uses rails). I know rails pretty decently and have used javascript and learned it before (but just don't use it that "often" but can read it just fine outside of the more complex stuff/new ES6+ stuff)
Would it be better to just learn react straight up and learn any missing JS along the way? I can understand most written code just fine but didn't know if it was worth it to learn JUST js to learn react (to integrate with rails). I've made basic apps in the past with JS (on freecodecamp and such) but don't really use it much in daily life (mostly use ruby) so obviously there are things i've forgotten.
(Also is stephen grider still the recommended udemy react course?)
Thanks
1
u/blaqsquirrel Sep 14 '19 edited Sep 14 '19
Hey y'all! New to react but wanting to get my hands dirty with it. I am attempting to build an admin console using react-admin. I've been able to pull in test JSON data and style it and allow the front end user to edit it, which is great but what I need to be able to do is grab the data from an API that has a security type of OAUTH2. I'm not even sure what to look up to find an answer or tutorial for this. If I can get the final json file then I can do what I need to do with it but I'm not sure how to connect that bridge. Any help or suggestions are greatly appreciated.
Attempting to use the brightcove CMS API:
https://docs.brightcove.com/cms-api/v1/doc/index.html
1
u/jammastahk Sep 16 '19
I recently went through a Bootcamp where we breezed through React. From a higher level I understand what we're trying to accomplish with Components and the like. Where it really gets lost on me is props. I know that props are a piece of UI that is rendered on the screen. But what I don't understand is when I should use them or where or how. For instance, I have a website that I am building for my wife's Jump Rope Team using Bootstrap. I'm wondering how I would incorporate props into my application. Here's a small example of what I have currently. I have a lot of components that just have basic jsx (Bios, About the Team, and events). I will have a Contact form as well (not built yet). Given the below is there a way to incorporate props or am I missing something about the way they work?
1
u/load_up_on_hummus Sep 16 '19
I want to begin making my own React apps, but I'd like to form an efficient design workflow first before I ever even begin typing code. I develop on a Windows machine. Are there any good UI design tools that can export React components in their full glory? I looked at Webflow, but I have to upgrade to a paid plan in order to export any code...
1
u/dadadadamattman Sep 17 '19
Does anyone know of a good tutorial on authenticating with a back end? I have not been impressed with the tutorials I have found so far.
1
u/hurrdurrderp42 Sep 18 '19
Can I put one method of a component inside another? I'm creating the same query to send in a request in multiple methods, i'd like to put that into a separate function.
1
u/commanderCousland Sep 18 '19
I'm relatively new to React and am wondering how to go about building a react webapp generator. Can't seem to find any good resources for it. Any advice would be appreciated.
1
u/liohsif_nomlas Sep 19 '19
Hi, I am trying to have my React/NodeJs/Express project deployed onto Heroku, but I am running into some issues. After pushing my project to heroku git and then loading the given url, I was getting a white screen with just "Cannot Get /" . I found out that I had to include these to set the static files:
I tried testing it out on a localhost and once the above code was added I no longer get 'Cannot Get /', but instead I am getting errors such as "Error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data" and I am also getting errors where "this.state.someName is undefined" and a "this.props.location.someName is undefined". Whats strange to me is if I take away the app.use and app.get that I added above everything works fine on the localhost (I used create-react-app and when I load up my project on localhost:3000 it works perfectly fine without the app.use and app.get)
I am thinking theres an issue within app.get and the app.use I added? My understanding is app.use(express.static .......) points to the files you will be using for frontend. This is rather confusing to me and if anyone can give me some advice it would be much appreciated.
1
u/jammastahk Sep 19 '19
How do I style text within a particular string? For instance...
HTML:
<p>This is some text. <b>This is bold</b>.</p>How would I do the same in React? Is it acceptable to do the above? Or is there a way to add styling via a variable? I've searched and searched but all I'm coming up with is information about React Native.
1
u/guitnut Sep 19 '19
Hi, I've replied in a thread to my original question where I got help from u/dancetodie but I'll appreciate any other help.
Link to thread - https://www.reddit.com/r/reactjs/comments/cy93lg/beginners_thread_easy_questions_september_2019/f0refjo?utm_source=share&utm_medium=web2x
1
u/AmpyLampy Sep 19 '19
Hey I'm trying to get up and running a tumblr clone using react frontend and postgres/node/express backend, but I'm very confused with JSON webtokens.
The current system I want to use is having refresh tokens with a decently long expiry date (7 days) and a auth token with a very short expiry date (1h)
This is my current system:
Every time the user makes a request to a protected route, the server will check the auth-token cookie. If it isnt expired, then all is good.
If the auth-token has expired, or there is no auth-token, check the refresh token. If the refresh token is valid and exists in the database, allow the user to pass and return a new auth-token back, replacing the old auth-token cookie.
If the refresh token doesnt exist/is invalid/not in the database, then reject access to the user.
Now here are all the doubts I have:
Every other tutorial says that "storing tokens in cookies/localstorage is bad because they are vulnerable to XSS/CSRF attacks" 1 [2] (https://stackoverflow.com/questions/53668165/where-is-safest-to-store-json-web-tokens-jwts-in-client-side).
So where do I store them? Store them in headers? Store them in a database? I feel like storing them in a database defeats the purpose of using JWTs (even though I store refresh tokens in a database anyways, because it feels like im just doing session-based authentication. I may be wrong here). Or is it more of a "every method has its drawbacks and advantages, and I should choose one according to my needs and try to mitigate those drawbacks?"
1
u/AmpyLampy Sep 19 '19
When I'm fetching information from an api, this is what I do:
I feel like doing an
await this.setStateis a react-antipattern. I put it there because I know thatsetStateis an async function. Should I change the way I am fetching and setting state?And in general, is turning lifecycle methods like
componentDidMountorcomponentDidUpdateasynchronous a bad practice?1
u/workkkkkk Sep 20 '19
Any alternatives to something similar to https://www.npmjs.com/package/react-grid-layout (react-grid-layout). It's really great but seems like it has largely been abandoned since last publish was two years ago.
1
u/argiebrah Sep 20 '19
Hello guys, its me again. In the process of creating an app with react, node, node-postgres and of course PostgreSQL, inserting data from react and send it to the database works just fine. The problem is I have to press F5 to see the changes I submitted on the front end. My backend is not asynchronous, therefore making it asynchronous would that solve the problem or I would have to use socket.io? The code I used in the front end is a bit below and I used preventdefault to prevent the refresh of the page.
1
u/cstransfer Sep 21 '19
Any types of unit tests that you add that most people normally don't? Does anyone unit test responsive design?
1
u/NickEmpetvee Sep 22 '19 edited Sep 22 '19
I'm using react-sortable-tree, which allows browser tree views of data. It's possible to embed forms on a node of the tree independent of other nodes. I'm trying to have a Select in the node that triggers the form submit when it's changed. Can someone advise on how to do this? Code:
Please note the attempt to submit near the bottom which fails.
1
u/madalinul Sep 23 '19
Hello, this question is not really react specific but I don't know where to ask.So i am building two apps, one will be just like a modal and would be public and a bigger app that includes the modal app.
How can I build and debug the modal app inside the big app? If i put the small app inside the big app src babel throws some errors and i think it's to the fact that the modal is standalone, with it's own package.json and build configuration.
Is there a solution to this or have you guys encountered this problem?
1
u/SuddenFlame Sep 23 '19
Just wondering what the most popular solution for creating isomorphic react apps is these days?
Am considering coding up my personal site in react (for run) but want to explore how I'd get SSR working.
Is this a big job, or are there libraries that can take care of this?
1
u/vnlegend Sep 24 '19
I have a question regarding React-Native and redux. I have a screen that subscribes to redux and need its variables as props. I want to logout, which will call an API, clear the store, and redirect the user to another screen.
The problem is when the store is cleared, the screen is still subscribed to redux and may get errors accessing nested variables. Redirecting first will unmount the screen and the logout function won't fire.
I guess I can redirect to another screen that doesn't depend on redux, then logout. This may cause a flicker or something. Or redirect to the login page and call logout from there, which seems messy. Any other good solutions?
1
u/Herrowgayboi Sep 24 '19
Is there anyway to create and build a project on a USB drive? I need one to transport. Git would be an option if I had internet all the time, but I don't.
My only issue right now is that Create-react-app stops mid way through creating the app when running on my USB...
1
u/epitaphb Sep 25 '19
My project has a modal dialog, which I've got working, but I'm trying to figure out a simple way to handle the tab focusing for it. Everything I've tried googling seems really complicated or just points me to the react-modal component, but I'd like to figure out how to do it on my own. I have a ref on the close button which focuses on opening, but what's a good way to keep focus cycling through buttons/links within the modal itself?
1
u/drdrero Sep 25 '19
Currently developing a socket game in React - Redux. Coming from Angular 8 where everything is an Observable i could easily listen to state changes and trigger simple events. But i don't get the flow with React & Redux.
I can dispatch actions for changing data. But how can i react to data being changed? For example, i want to listen to a socket event, when this happens, an animation should be triggered. No data needs to be included just a simple void event somewhere down the component tree. The socket handler dispatches an action and my current approach is that i store an rxjs Observable in the store and .next() it in my reducer like:
case "ROLLED_DICE":state.rolledDice$.next();return state;Now i can easily listen to that observable in my deeply nested component.
1
u/gabrieljim Sep 25 '19
Hey everyone! I'm working with Routes for the first time and I'm trying to make a "go back" button, but I'm super lost on how to do it. I'm also using functional components and hooks because it's all some stuff i've never tried before.
Anyways, here's my attempt:
I really hope I can get some help with this, thanks a lot in advance
1
u/blaqsquirrel Sep 26 '19
Hi All!
Could someone point me in the right direction for a tutorial or documentation on allowing the user to sign up and choose a name and with that name build a branch under my domain? For example, if they were to be "Company A" then they would sign up and a build would be deployed and built under mydomain.com/companya which would would be their home and login.
1
u/Erebea01 Sep 27 '19
Hey guys what's the correct way to implement fetch in functional components and hooks
I tried this but won't get the correct response, I switched to the below class method for now and it works
1
u/WhiteKnightC Sep 27 '19
Hello my dudes I just finished the Tic-Tac-Toe tutorial challenges and wanted to check if you could correct me, link.
How I solved every point in this site:
Display the location for each move in the format (col, row) in the move history list:
Could be done with state?
Bold the currently selected item in the move list:
}
JSX is weird.
Rewrite Board to use two loops to make the squares instead of hardcoding them:
JSX is weird part 2.
Add a toggle button that lets you sort the moves in either ascending or descending order:
I kept moves as a const.
No idea yet, I skipped it without knowing.
When no one wins, display a message about the result being a draw.
Winner: No one.
Thanks for reading!
1
u/e_pluribus Sep 30 '19
I've been developing with web/mobile tech for ~20y, and I'm just getting into React. At first I was skeptical, but I recently built a type-ahead search component and had a great experience with it.
Some of my teammates are big on Redux. I get the value of centralized storage of state, clear history for debug/undo, and general communication between components through data changes.
However, I also value encapsulation, and was taught early on to only making public that state/behavior that other parties have any business reading or manipulating.
So it's my inclination that for a search results pagination component, local data and behavior to the component (such has how to sort, or which page we're on, or what the current page of results looks like), that should be stored privately in that component.
Am I wrong? Is there a case to be made for "Damn the torpedoes, store all state in Redux"?
1
u/blaqsquirrel Sep 30 '19
Hey everyone! Iβm new-ish to ReactJS and it is definitely not my strong suite. I have a package I want the client to be able to install on my server. For example, they go through a form workflow and upon completing it, they choose the name - say βCompany Aβ and when they hit complete then a package will be deployed on my server and making it accessible at www.mydomain.com/company-a
Is this doable? Can someone point me the direction of some tutorials to achieve something like this?
1
u/Goshawkk Sep 30 '19
Worked with React for a while, trying to learn TS now. I often do this in render:
So validation is just null and doesn't render anything if I don't need it to. Where ErrorText is defined outside of the main class. I can't figure out how to correctly assign types to the validation variable though? Whatever I do TS complains. e.g.
let validation: FunctionComponent<{text: string}>;
gives
Type 'Element' is not assignable to type 'FunctionComponent<{ text: string; }>'.
Thanks.
1
u/jp2y Sep 30 '19
hey guys, complete react noob here.
i am currently having a problem when i use 'npm start'. i am getting this error.
help would be greatly appreciated. thanks in advance!
edit: i followed the instructions shown in the terminal to fix it. it didn't work.
1
u/[deleted] Sep 30 '19 edited Sep 30 '19
So, I'm mostly a newbie in React and CssGrid. I'm building a single page app with React router for navigation that's supposed to work on laptops and phones.
It has a homepage and 3 navigation level pages (about, team members, login).
Each navigation-level page including the homepage will be split in half (hence the need for css grid) with the right half being the header and a short main "thing" (contact info, sign up link, etc.) and the left side being a scrollable list (sometimes pictures, sometimes events, etc) .
When opening on the phone, the left section goes under the right section.
I'm using React, with separate components for each of these sub-sections. How do I add css-grid to all of them to do this split style without unnecessarily repeating code or adding too much css overhead when loading the page? Google isn't giving any good guides on using CSSGrid with React.
PS: I'm using vanilla separate css stylesheets and importing them to each component and one main one for the App component, bc I'm a noob and IDK what's a better way. Saying this bc the archived thread I found on here wasn't helpful but they asked the OP about this). Hope I provided enough info, and thanks for any help :)
Edit: I didn't include code as the components are barebone and I'm mostly looking for online guide recommendations on how to use cssgrid with react and/or a code-sample with a suggestion from one of you lovelies.
If it helps, You can think of my app at a very basic level using
<App><Home><Header /><Right1 /> <Left1 /></Home>OR
<About><Header /><Right2 /> <Left2 /></About></App>1
u/carlsopar Sep 30 '19
I have an array of objects, that I want to split on a key value. This will be split into two different arrays based on the key "found" being true/false. I also want to be able to change, and add data as well. For example I want to be able to update the name "Paul" to "PAUL" or change found from true to false. This will result in an update to the main array as well as the split arrays.
Should I be using a using useReducer and then split against the arrays? What I would like to do is only update the main array and have everything update against it. Suggestions or ideas, would be greatly appreciated.
const NamesList = [{name:'Paul',age:33,found:true},{name:'Michelle',age:32,found:true},{name:'Erik',age:30,found:true},{name:'ruth',age:69,found:false},{name:'patty',age:59,found:false},{name:'steve',age:60,found:false},{name:'mike',age:73,found:false}]0
u/[deleted] Sep 05 '19
[deleted] β view deleted comment
0
u/[deleted] Sep 08 '19
[deleted] β view deleted comment
0
u/[deleted] Sep 10 '19
[deleted] β view deleted comment
0
u/[deleted] Sep 14 '19
[deleted] β view deleted comment
0
u/[deleted] Sep 16 '19
[deleted] β view deleted comment
0
u/[deleted] Sep 17 '19
[deleted] β view deleted comment
0
u/[deleted] Sep 06 '19
[deleted] β view deleted comment
0
u/[deleted] Sep 18 '19
[deleted] β view deleted comment
0
u/[deleted] Sep 23 '19
[deleted] β view deleted comment
0
u/[deleted] Sep 28 '19
[deleted] β view deleted comment