r/reactjs • u/timmonsjg • Apr 01 '19
Needs Help Beginner's Thread / Easy Questions (April 2019)
March 2019 and February 2019 here.
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?
π 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!
3
u/snowboarder56438 Apr 16 '19
I am currently working on a very data heavy app. As it stands now I basically have one main component with one state item and which is passed as a prop along with an on change function for each bit of the item. Is this the best way to do it?
A simplified example would be the main component is a customer the customer has a contact component, a history component, etc... Each one would have multiple components of their own. Then the contact component would be passed onContactChange(), a method to change the top level customer state, as a prop along with the top level customer object as a prop to populate the data in contact.
2
u/anewlens Apr 13 '19
I used create-react-app to build and deploy to Github Pages. Say I need to do update the app, do I rebuild and redeploy? or is there a simpler way to do it? or harder?
2
u/japhex Apr 17 '19
Hey guys! Quick question about HOCβs, I have HOC that is connected to a redux store and has a couple of api calls/shared methods in it.
I can wrap a top level presenter in this and it receives everything as props just fine.
My question is can you wrap multiple levels of components in a hierarchy in a HOC rather than passing props all the way down?
e.g.
DataHOC
DataHOC(Template)
Rather than
DataHOC
DataHOC(Template)
I tried it but the API calls in the HOC then fire multiple times, which does kind of make sense!
My use case is that Iβd have some components that are pretty nested so I just end up passing a prop from Template through about 5 components and itβs only used in the one at the bottom of the tree.
1
u/javascriptexpert Apr 01 '19
combineReducersadded one more level of nesting for my state.I am learning redux. When I divided my long reducer file into multiple files and did
combineReducersas per the udemy course I started seeing one more level of nesting.CodeSandbox link: https://codesandbox.io/embed/jjj7mjyqp3
Now I have to go one more level deeper in my
mapStateToPropsto get theresultsandcounter. Is there a better way to do it? I definitely see this is not the correct way to do mapStateToProps.1
u/Sunwalker Apr 01 '19
Can anyone recommend a 'complete project' turorial? For instance, I've followed several 'how to create a blog' tutorials but none of them actually create a full working product with user authentication and roles and such.
I feel very confident with my front end react skills but have very little confidence tying it to user authentication and creating a real app.
A push in the right direction would be appreciated.
1
u/I_literally_can_not Apr 02 '19
I am totally new to react, and yesterday I made my first react based app yesterday, check it out here: https://student.labranet.jamk.fi/~L8314/etteplan/
It is running on react 15.4.2, and I was thinking about upgrading to the latest versions, but if I even change the links to 15.6, it just breaks the page.
I have looked a bit into npm, but i don't really know how to use it at all. I tried downloading react with npm but it just spits out a bunch of warnings and stops.
I know I shouldn't break it if it works, but i would just like to know what you would do to upgrade the react packages.
The app I made in the link above was handwritten, so npm probably wont work with it. (or will it, I don't know)
1
u/cokert Apr 02 '19
What's the "best" way to handle loading details in a list/details/edit scenario when using react, redux, and react-router?
In my project's current configuration, if a user navigates from the list view to the details or edit view, the form container finds the particular record in the store and passes it to the form component via props. The form then saves that record to its internal state in its constructor (the form has a lot of fields and will have involved validation rules, hence it having its own state). If a user loads an edit URL directly, the store doesn't have the list of records loaded and the record is null when the form component renders. In this situation, the form component requests the record from the back end API directly using a promise, and sets the state when the promise resolves. This completely bypasses redux and kinda doesn't really feel right.
My other option is to use redux, obviously. I have actions written to request a single record that I could dispatch, but the form would already be rendered by the time the store is updated and I'd miss the opportunity to set the state in the constructor. I could use one of the lifecycle functions (getDerivedStateFromProps() or shouldComponentUpdate()) to get the newly loaded record into my state. But I don't know if that's the "best" way, either
My gut says that the "best" way is to always request the freshest data from the server in an editing scenario, which would mean that the form component should *always* load the record via the API, even if that record currently exists in the store. But ... idunno. Anyone have any thoughts?
1
u/[deleted] Apr 03 '19
What are some common patterns used for an app's routing that can scale in terms of breadth (think subapps 7 of an app) and depth (3 layers down, app, subapp and the dynamic routes for subapps)?
I've been playing around with several types of patterns to make it easier for my team (we're all relatively new to programming) and all the solutions we could come up with involved at least 3 nested switches and it gets really complex by the time we hit the dynamic routes so I was wondering if there were any open projects we could learn from.
We tried mixing different patterns to solve the issue in layers, (for example, using a layout and switch to the different routes in an app for the sub apps layer) but eventually we seem to keep hitting snags at the lowest layer involving dynamic routes.
What would be your perspective to this problem, maybe she'd some light on how we've missed some perspectives out!
1
u/_RayT Apr 03 '19
HI, I am trying to use Redux to do state management, and then I stumbled
redux-thunk, which looks great for centralizing API call within Redux, but I am now stuck at the point where the AppState is too fragmented,I have
LoginActionStore(for handling login, post to the server and storing any login error)LogoutActionStore(for handling logout, post to the server and store any logout error)CurrentLoginedUserStore(which is used to manage login session)and the data repeated themselves all over them, I have userId info in all the mentioned store.
Any article/website for designing a better StateStore structure?
Thanks
1
u/Bombuhclaat Apr 03 '19
Really not sure I get the difference between "this" in ES5 and in ES6
I can't refer to the state with "this" without an arrow function?
1
u/KSeanJBz Apr 04 '19
In my app.js I have my react router and I am doing authentication checks. I do an api call to pull user data and save it to a state. I then pass it via props to any other components that may need the logged in user data.
Is it more efficient to do a
on every child component so i can reduce api calls or is it better to do just do another api call to pull user data on every child component that needs it?
1
u/flurmbo Apr 07 '19
Hi, I am writing a React component that displays some text, and it will be used in multiple areas of our app. In some contexts, it will need to display a different message on the web app than on mobile devices, like this:
In other contexts, it will display the same message regardless of the platform. I was wondering if there's a pattern that allows me to use the above code in the first context and in the second context to use this:
Right now, I have something like this at the top of my render function:
Is there a better way to do this? Or is this all a bit overkill and should I just be satisfied with something like this:
Thanks for any help!
1
u/BargePol Apr 11 '19
Are their any better aesthetic solutions to including multiple HOC's in a component than the one I have? I.e:
export default withAppContext(withMenuDialog(withInputDialog(Component)));1
u/argiebrah Apr 12 '19
I have a question. Why are employers more attracted to candidates to hire with CS degrees with absolutely no knowledge in React against a self taught developer with react projects made and deep understanding of HTML, CSS SASS and Bootstrap?
1
u/Dantharo Apr 14 '19
I have a question about arrow functions.
Why this work https://pastebin.com/uLf5A1vD
and this not work https://pastebin.com/CVcje8NP ?
The only difference between them is the arrow function in the fetch
I got "Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined" when not using the arrow functions.
1
u/[deleted] Apr 14 '19
I'm just working on a basic ToDo App, and I've figured out how to add/delete items, but editing items gives me a lot of trouble.
The items that have been added are displayed with the
Array.map()method into an unordered list, plus an edit button and a delete button. What I want to happen is for the<li>to change to an<input/>tag when Edit is clicked, then for that<input/>to change back to an<li>after Update is clicked.Or if there's a better way to do this, let me know.
1
u/trojans10 Apr 16 '19
I'm planning on building a large scale content authority website. I was thinking of using wordpress/php to launch - but really like how smooth react/nextjs is. SEO will be very important for me. I'm wondering if there are downsides if I choose react/nextjs... I'm familar with wordpress, and am learning react now. So it would be a good learning experience but at the same time, I plan to make this website quite big.
Anyways, any opinions? And if I do go with react - any advice when it comes to a large scale authority website mainly with content?
1
u/Unchart3disOP Apr 17 '19
I am building a twitter-like react app where I am using redux such that it has a store -global state- for the Authenticated user -stores the data about the user that's currently logged in- and I am thinking of adding another global state such that it contains the data of the profile being visited at the moment, is that a good idea or should I rather store the data for the visited profile ONLY in the local state of the profile component, if this is abit confusing feel free to ask me whatever you want thanks
1
u/cryinjordan Apr 23 '19
When should I make a component an arrow function or a class? (or when should I use arrow functions in general)
1
u/maestro_man Apr 23 '19
Hey all! Pretty new to react. Couple questions for the community:
Thanks so much for your help! Cheers!
1
u/[deleted] Apr 23 '19
Hey pros!
I have been just about everything else I could do before tackling this one but I'm here now and it's getting me a bit flustered.
I am making categories out of an already retrieved data set (grabs data during initial mount and held in most parent state) and would like to match the sub string of a users input (text from the search bar/form) with what is inside a particular property in each object.
I was thinking I would map through the array of data , & conditionally filter through that data within the same component then assign each new 'category' array into that components state for rendering..
Link to dataset (JSON)
stale data I know - but I already built half of this ship and I need it to sail far away from here.
Is this an awful approach? I am going to have to dig deep now and don't want to waste all of my time..I need to get over that though.. If this is the right approach.. would any of you mind giving me some pointers? This is the part of this application that I knew would grind my gears a bit.
1
u/[deleted] Apr 25 '19
Hey guys. I'm doing simple small business/brochure websites with mostly plain html and css. I just jumped into react (and gatsby) for some more complex stuff (wp integration) but mostly because I think it can bring my dev experience to the next level.
So at the moment I'm basically trying to update my templates (the layout/design part) from pure html/css to gatsby and I am having problems figuring out what the best way is to implement different navbars (Top Nav Bars, which transform to a Sidebar Module when on mobile/small screen; burger menus with a full screen modal when clicking and so on).
Right now I basically stick to the gatsby-default-starter layout and folder style:
I feel this is not the best way to structure projects, especially with complex navigation bars which have several components alone?!
I love the speed of gatsby but as soon as I want to build a more complex navigation type (more complex than the typical simple topnav) it seems to get really messy and complicated compared to the way I would build it in html/css.
So maybe you guys have some tipps/insights for me?
1
u/[deleted] Apr 25 '19
Hello, I am a beginner using React and I want to make my first test (i'm learning
react-testing-library), the thing is that I have a connected functional component with useEffect hook which gets the character list data by running a saga. I want to send fake data like this:
const mockDataGet = {data: [{id: 1,charname: 'Warrior',level: 1,},{id: 2,charname: 'Thora',level: 4,},],}
and check if it renders 2 Character components. How I am suppose to make a test for it?
COMPONENT
import React, { useEffect } from 'react'
import { connect } from 'react-redux'
import { ListGroup } from 'reactstrap'
import PropTypes from 'prop-types'
import { selectCharacter, fetchCharacters } from '../actions/characterActions'
import Character from './Character'
const mapStateToProps = state => ({
character: state.character,
})
const mapDispatchToProps = dispatch => ({
fetchCharacters: () => dispatch(fetchCharacters()),
selectCharacter: id => dispatch(selectCharacter(id)),
})
const CharacterContainer = (props) => {
const {
character,
history,
fetchCharacters,
} = props
const handleClick = async (id) => {
const isSelected = await props.selectCharacter(id)
if (isSelected) {
history.push('/game')
}
}
useEffect(
() => {
fetchCharacters()
}, [fetchCharacters],
)
return (
<ListGroup>
{character.map(char => (
<Character data-testid="characters" key={char.id} id={char.id} charname={char.charname} level={char.level} handleClick={handleClick} />
))}
</ListGroup>
)
}
CharacterContainer.propTypes = {
character: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
charname: PropTypes.string.isRequired,
level: PropTypes.number.isRequired,
})).isRequired,
fetchCharacters: PropTypes.func.isRequired,
selectCharacter: PropTypes.func.isRequired,
history: PropTypes.shape({
push: PropTypes.func.isRequired,
}).isRequired,
}
export default connect(mapStateToProps, mapDispatchToProps)(CharacterContainer)
REDUCER:
type CharacterAction = GetCharacterType | AddCharacterType | OtherAction
const characterReducer:Reducer = (state = initialState.character, action: CharacterAction) => {
switch (action.type) {
case ADD_CHARACTER:
const { character } = action
return [
...state,
{
charname: character.charname,
level: character.level,
id: character.id,
},
]
case GET_CHARACTERS:
var charactersList = action.characters.map((char:CharacterType) => ({
charname: char.charname,
level: char.level,
id: char.id
}))
return [...charactersList]
default:
return state
}
}
SAGA:
export function* watchCharactersSaga() {
yield takeEvery(actionType.FETCH_CHARACTERS, getCharactersSaga)
}
function* getCharactersSaga() {
yield put(clearForm())
try {
const character = yield call(characterService.getCharacters)
if (character) {
yield put(getCharacters(character))
} else {
yield put(errorForm('Could not fetch character'))
}
} catch(err) {
yield put(errorForm(err))
}
}
1
u/Zyandor Apr 26 '19 edited Apr 26 '19
Hey, been usng react for a while now and just came across a weird issue in my site during testing. For some reason an event is not dispatched on the first click of the button "Arrow". As well as this, the console.log's do not fire until I have clicked the button.
Anyone better at this stuff than me able to point me in the right direction?
class PageBottom extends Component { constructor(props) { super(props);
}
1
u/lord-bazooka Apr 26 '19
Can you help me out with the question that I posted on StackOverflow about React Router params?
https://stackoverflow.com/questions/55867108/use-route-param-as-array-index-in-react
1
u/cag8f Apr 29 '19
Hi all. When my React app loads, I will define a single constant that will not change. I then want to pass this constant to a function in my top-level parent component. What is the best way to do this? Specifically, where/when should I define the constant, and how could I then pass it to a function?
render()function. Inside the <script> tag could be code that defines the constant. Then I could pass it to a function--correct? But I would have to take care that the constant isn't constantly re-defined every time therender()function is executed. I could possible do that with a conditional to check if it has already been set?my_constantincomponentDidMount(). But I couldn't figure out how to pass it to a function--I kept encounteringmy_constant not seterrors.In this case, the constant is a large object. And to 'define' the constant, I must make an HTTP request to an external API. So I am trying to avoid having to do that over and over.
Thanks in advance.
1
u/[deleted] Apr 29 '19 edited Apr 29 '19
I have a
Layoutcomponent with a Header:I can switch between
./Headerandorg-headerwhich is the same as./Headerbut in its own npm package and added vianpm link org-headerThe problem arises when I try to use Layout in the context of Main.js:
When
Layoutuses./Header,Containerpicks up on the custom styling, but when usingorg-header,Containerdoes not have any styling. What's going on?1
u/tangobacon Apr 29 '19
What React's Design System you guys are using in your webapp (Segment, Uber, Atlassian, etc)?
1
u/classicwfl Apr 30 '19
Any good resource that's up-to-date for regular newbie stuff? I just started working in React, and I'd like something that would make a good reference while I'm building (when to use a class and other common React stuff). Bonus if it also covers ES6/7.
1
u/calumwebb Apr 30 '19
Hey,
I'm trying to create this in react and really struggling with the border (the #s in particular), anyone got any advice
https://imgur.com/jpNtfpk (changes state when hover, i can do the hover etc but just not the # border)
1
u/argiebrah May 01 '19
What Should I do If I can't get a job with React as a front end dev, keep learning and do more complex projects? Or learn a back end language like node.js? Already know HTML CSS and Javascript, as well as react router, some d3.js and some PHP coming from Wordpress. Thanks!
1
u/tortita-fg Apr 18 '19 edited Apr 18 '19
Are literal objects such as switch statement outdated in functional programming?
Hi guys,
Developing (in React) I found that I had to click on a button to add or remove favorites therefore and tried to perform a general function that encompasses all cases leaving aside combined conditions and switch not to enter a tree of conditions. The function (typed with Typescript) would be as follows:
Is this (literal object like switch statements) an antiquated form of functional programming?
I would like to know what the current trend is, whether by tutorials, web or if anyone has a lot of knowledge about it.
I'd like to know the community's opinion about functional programming within React or in general and if anyone has a cleaner and more elegant way to transform this into functional programming that exposes it to me, or some post, tutorial, book, etc, all in order to learn more.
Thank you very much in advance.
Best,
2
u/Unchart3disOP Apr 06 '19
First off, I am not sure if that's the right place to post this if it's not feel free to tell me tho.
I couldn't participate in this year's GSoC and it kinda sucks cause it's a great chance to improve my React skills, however, I still want to contribute to open source but I am new to all this how do one find good projects to contribute to which also use React -and that would be suitable for a beginner- Also if you could choose between one of the two: Contributing to open source or building your own React projects which is the better one to develop your skills with React + have a solid CV for an entry level front-end engineer?
Thanks
2
u/ibored107 Apr 07 '19
Has anyone ever encountered a NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node. because of a state change? If so could you help me answer my question on stack overflow?
https://stackoverflow.com/questions/55554041/reactjs-notfounderror-failed-to-execute-insertbefore-on-node
2
u/node_user910253 Apr 19 '19
Sorry if this isn't the best worded question, but basically for my project I have a form that sends a get request to the server, where it queries for results in my SQL database. I want to take the results, and send it off to index.js to be rendered as part of a page.
I'm not sure how I would achieve this, and I would appreciate if anyone could give some insight into how to solve this.
2
u/Diasjunior Apr 21 '19
I'm creating my first app in react as a challenge for a job interview but this is the first time i learn react. The challenge asks me to run an API locally (which was built on parse server) and fetch some data from it. The problem is i can't communicate with the API. If i just connect to the localhost on the port its listening to it gives me user unauthorized. The challenge gave me credentials for a user that is registered on the database this api uses so i believe i need to create an object of this lib (parse server) to comunnicate with the API but i can't figure out how to import this dependency into my react project. Can someone help me with this?
2
u/Entropis Apr 22 '19
I have a header Component that has some state attached to it that allows me to show/hide the header onClick. I have another Component, not attached to the header (It's part of the content, let's say) below it. Is it possible to dynamically change the height of the second component when the Header Component is shown/not-shown? If so, how would I go about doing it?
2
u/[deleted] Apr 23 '19
Hello,
I've been working on free code camp's first React Project: Building a Random Quote Generator.
The goal is to display a new random quote (no repeat quotes) on each click of a button.
I'm about 90% of the way there.
The source of my quotes is a 2-d array of a quote and its author. In state I'm tracking the original quotes array, an array holding quotes that have been used, and lastly the current quote being displayed.
The main theme of my code is to splice out the current quote from the source array, display it, and concat it to the usedQuotes property in state. This way I don't repeat a quote. When the source quote array runs out of quotes, I reset all state properties to their default values.
The only problem I have now is there is still a small but definite chance of quotes repeating when the last quote spliced is the next current quote when the state properties reset to their defaults.
I've looked at the documentation for lifecycle methods and thought componentDidUpdate() might help but am unsure if this fits the current theme of my code. If I use this method I feel I might be better off comparing current quote to next quote instead of splicing out quotes.
I've been working on this over a month and am completely stumped. I've looked at other people's examples and most of them seem to repeat-they just have a lot of quotes in their source array so it seems to not repeat.
Here's the link to my code: https://codepen.io/SuperBeowulf/pen/OddoVW?editors=0010
2
u/badboyzpwns Apr 27 '19
Newbie syntax question, why is the first picture the same meaning as the second picture?
π·
https://gyazo.com/586221c8c00408935720858806d5cc8f
The second picture made the function into a self-invoking function...instead of just returning the object.
https://gyazo.com/0c2d431ec1f1780361bd284316f07ddd
1
u/ericnr Apr 02 '19
more of a Formik question but I really can't find the answer anywhere else. Can I pass my state to formiks initial values while using withFormik and not the <Formik /> component? something like this
https://imgur.com/jSU5Svl
1
u/Kazcandra Apr 04 '19
React-Redux question. In my app, I have several
categories, each category has severalarticles. I'd prefer to keep my state flat, so I don't want to do this:Because that'd be a pain to update (I will, in the future, need to be able to update both categories and their articles). Everything is backed by a backend API that really doesn't matter here. Initially, I figured that I'd use two reducers, one for categories and one for articles, meaning that I'd do something like this for categories:
The CategoryReducer will produce
categories: [], selectedCategory: number, and I figure the view for articles will listen toselectedCategoryand draw the proper list. But, before I start working on this solution, I kinda wanted to ask if there's a better way that I'm maybe not seeing? Is there a pattern I'm missing?Edit: it is likely that backend-wise, it will be a
has_manytohas_manyrelationship, meaning that articles can belong to many categories and that categories has many articles.1
u/php_developr Apr 04 '19 edited Apr 04 '19
How hard is it to get babel transformers into a non-CRA React app? I'd like to make an admin section for a Wordpress (php) site inside <script> tags.
I've only ever done React projects with CRA and it seems manual setup of a React app is almost as complex as React itself!
My 2 main concerns are:
EDIT: Looks like adding JSX support only requires another external resource: https://reactjs.org/docs/add-react-to-a-website.html
Still curious about #2 though. I suspect without a build step I can only use libraries that are CDN hosted and have script links available
1
u/BitLooter Apr 05 '19
I'm building a project with CRA that operates on files downloaded from the server. Currently I'm putting them in public/ to be available on the development server. However, these are just test files and different data is used in production, but they end up in the build anyways. Is there a way to exclude files in public/ during a production build? Right now I'm using a postbuild script to clean up the output directory, which works but seems like a hack. Is there a better way?
1
u/Unchart3disOP Apr 05 '19
Hello guys, I am pretty new so I am not sure if that's the right place for this post.
I am building a web app that looks alot like twitter however I want to do this effect of whenever I click on a tweet, I'd like to have this particular tweet come up top with all the page behind it slightly shaded. I'd also like to set the comments on that tweet shown under it as soon as I do that. anyone got any ideas on how I can do that or which libraries to use for this "shading" effect thanks :)
1
u/Gueroposter Apr 05 '19
Hi guys!
Could you help me, please.
How to clear Input field after hitting Enter? I choose onKeyPress over onChange, so value from the input form pushes into an array only after I hit Enter. It works fine, but Input field doesn't clear itself :)
Or maybe there is a better solution with onChange method?
Thanks!
1
u/Rott92 Apr 05 '19
Hi guys, im trying to learn React but i don't know anything of front end development. I've tried some React tutorials, but always get lost when they start talking about Redux, Node.js, Webpack, Babel, React Hooks, Bootstrap, etc.
For someone that only knows Javascript, HTML and CSS(Beginner level).
What books or tutorials do you recommend?
Thanks.
1
u/dyesiboy31 Apr 05 '19
This also helpful also for the beginners like me. https://github.com/enaqx/awesome-react
1
u/Verthon Apr 05 '19 edited Apr 05 '19
Hey, I'm adding the Redux and I wonder if in central store I can get the whole data from server and then distribute it to components as global state?
If that matters I will briefly describe my application:
Router - holds every routes, starting point in root of app
App - home component which gets featured events (rendered as EventItems) from database,
Events - component which gets the all events (rendered as EventItems) from database,
EventItem - which represents single event container rendered inside of App and Events components,
contains a link to route .../events/eventId which renders Event component.
Event - single component not related to any component except Router, thats why I'm adding Redux to pass EventItem state to this component.
Thanks for the help.
1
u/johnnykoo84 Apr 06 '19
Thanks for the post
1
u/CasinoInMyHair Apr 06 '19
Is having a lot of document.getElementByIds and event.targets sprinkled throughout your components a bad practice? Should props and state be handling as much DOM manipulation as possible? If an element is assigned a class via a prop in JSX vs. element.classList.add() in a handler method, does React do it in a more "intelligent" or performant way?
1
u/cag8f Apr 06 '19
I've created a new React project on my (Windows) computer, using
npx create-react-app my-appWhat is the proper way to remove this project from my computer? Can I simply delete the folder? Or is there a more robust method to uninstall it?
Thanks.
1
u/NickEmpetvee Apr 06 '19
How can I access a Context in a const?
Below is an const called
authenticateUserfrom Tyler McGinnis' tutorial on using Routes to manage authentication. It contains a few properties and functions.I have a Context defined ('SomeContext') in the application which houses a method setAuthenticatedUser(UID, userName) that tracks who is logged in currently by assigning the parameters to state values. In the below authenticate(...) method, I'd like to call this Context method as soon as the authentication is successful. I have a similar function that needs to be called on signout.
How can I accomplish this? Hooks?
1
u/agreatkid Apr 07 '19
If anyone has experience with using React along with Firebase (specifically Firebase Cloud Messaging), please help me out with a problem that I am facing regarding not receiving the onMessage payload. I have posted the problem on Stackoverflow:
https://stackoverflow.com/questions/55559020/firebase-cloud-messaging-onmessage-not-triggered-in-react-app-even-after-message
Thanks a lot!
1
u/khuongnguyen232 Apr 07 '19 edited Apr 07 '19
So I figure out that setState is asynchronous, just so I have somewhat following code:
" this.setState({favorite:newList});
localStorage.setItem('list',this.state.favorite) "
Basically I need to update the localStorage with the updated favorite State.
Is it a good idea to put await before my setState to make sure I update the localStorage correctly ? Or is there a better practice for this ?
p/s: sorry, not sure how to make the box for code yet
Edit: change βgetβ to βsetβ
1
u/Verthon Apr 07 '19
I have a problem with running React app (created with "create-react-app"), after clonning from GitHub and running npm install and then npm start React output blank empty div, without any error in console or terminal. I was developing it on Windows, right now I'm trying to run it on Linux is that a problem?
1
u/Hisiro Apr 08 '19 edited Apr 08 '19
Hi, i am making a react router but the problem is my component didn't show up, here is the code https://codesandbox.io/s/j7yl7nk7wy
1
u/[deleted] Apr 08 '19
What software / other stuff do I need to install on a new laptop to get started with playing around with React Native?
1
u/Xeon06 Apr 09 '19
Just started playing with React using create-react-app and I'm confused by how ESLint is supposed to work; is it supposed to output anywhere? I'm not seeing anything in the terminal (where I ran
npm start) and I even installed the VS Code ESLint plugin but am not seeing anything in the editor either. Maybe it's just super permissive?1
u/workkkkkk Apr 09 '19
This is a css question hope that's alright.
My understanding is that this media query should apply my styles on screens 1000px and below. However, when I use the chrome dev tools to resize the window the styles aren't applied until about 850px width. Anyone know what's going on or what I'm missing?
1
u/Xeon06 Apr 10 '19
What's everyone's workflow regarding running React apps (CRA apps specifically) through VS Code? I installed the Debugger for Chrome extension which is great for launching my app, but how do you guys usually launch the dev server? Just
npm startin terminal?1
u/ProfesorAlpha Apr 10 '19
Hi! im having re-render problems on a custom route whenever i do something on the component but cant figure out why
its done this way so it renders Producto on top of Documento as a modal when screen size > 1024
any input is appreciated
1
u/yagaboosh Apr 10 '19 edited Apr 10 '19
Sorry if this doesn't belong here, not sure if it qualifies.
I'm having trouble testing a component that does an async call to an API. I have set up a mock, and confirmed that the mock is working by calling the function in the test itself, and the results are correct.
The issue I am having is that the function is not getting called before React throws a fit that a state update is not taking place inside of an act() callback, which I do not believe needs to be done if I'm using Enzyme (and even if it did, I tried setting this up without Enzyme and got the same results).
I have done the same basic commands in the browser, and it works. The component itself is fine, but the test is not working. If it makes a difference, I am using React Hooks in all of my app, but this hasn't seemed to make a difference in testing my other components.
Any help is appreciated. Thank you in advance.
EDIT: Resolved, instead of using Enzyme I switched to react-testing-library, which still gave me an error regarding act() but allowed the code to work. Then, reading this thread I figured out why I was getting the act() error, and see that in React 16.9 this will be fixed. I didn't find anything on resolving the issue with Enzyme, but since RTL works I think I'll just switch over to that.
1
u/mynonohole Apr 10 '19
I'm starting to realize the value of planning and diagramming an application before coding anything significant. Just wondering what process (if any) do you guys use when planning a somewhat comprehensive app. Do some of you use balsamicIQ, draw.io, etc? Other methodologies such has test driven development?
1
u/hemiptera_reduviidae Apr 11 '19
I am trying to deploy my first React app to Heroku, but I'm having trouble with rendering images. I wrote about it on StackOverflow here: https://stackoverflow.com/questions/55637879/trouble-programmatically-accessing-image-url-in-react-app-when-hosting-backend-o
Basically, I have no trouble rendering images when I can do the src like this: src={require("../img/pink_fairy_armadillo.png")}
But when I try it with `../img/${props.message.user.avatar}.png` in any way it breaks.
1
u/TheRealChrisIrvine Apr 11 '19
What technology do I need to use to create a back end control panel for my users to edit the content of a website I make using react? WordPress?
1
u/Tonalization Apr 12 '19 edited Apr 12 '19
Hey all, Iβm hoping to get some help with a react-router issue. Specifically - I need to point my routes to components that are being loaded through src scripts. Hopefully this makes sense..
Iβm working on a micro services architecture project in my class. We each created a component, then built a proxy server to load all of the components onto the same page. Eventually the other components will be loaded through AWS hosting and a URL script , but currently Iβm running cloned versions locally.
e.g. from proxy index.html, proxy is running on port 3000
We tried to have as few inter-component dependencies as possible. However, I am working on the header component, and one of it's jobs is to render the overview/related-artists/about components below itself, using react-router to switch back and forth between them.
I used dummy components in the beginning.. and the routes obviously worked just fine. Here is the declaration and relevant imports:
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
Now that Iβm bring their components in, Iβm pretty stuck. Iβve tried several solutions using BrowserHistory and react-router-proxy-loader, but havenβt had much luck. I constantly run into this error:
VM10555 checkPropTypes.js:20 Warning: Failed prop type: Invalid prop 'component' supplied to 'Route': the prop is not a valid React component in Route (created by Header) in Header
Does anyone have a good work around? Hopefully this all made sense. Thanks in advance for your help!
1
u/erotic_sausage Apr 12 '19
Material-ui Textfield component outlined variant.
How do I correctly override disabled style? I just need a grey background. I've found it difficult to grasp from the documentation. I've copied a demo, and ended up with a theme using MuiThemeProvider. I've used inspect element to find the component base, which was either MuiInputBase or MuiOutlinedInput.
I've added a MuiInputBase object to the overrides object in my MuiTheme, and have styled the field I wanted. Yet, I get this warning in the console:
However, when I follow these instructions and instead use "&$disabled" I get the warning "You are trying to override a style that does not exist". Wtf?
1
u/kubelke Apr 12 '19
REACT TESTING
Hey, I got pretty big application. I would like to writing some tests but Iβm not sure where to start. Should I write unit tests or E2E? I cannot find good examples with mocking redux. I donβt know how to test/mock axios requests.
1
u/Watermelonnable Apr 12 '19
I came across a first wall. I'm not really good at css and I was using bootstrap all this time to help me develop interfaces, but now I see that bootstrap isn't so component friendly, meaning that this is not the right option to work with react... Am I wrong?
And... if I'm correct, what do you suggest to someone who isn't so good with css like me?
1
u/soggypizza1 Apr 13 '19
Anyone know any good JavaScript/React focused podcasts? I already listen to syntax but I need something in between the down time.
1
u/jkuhl_prog Apr 13 '19
I have a very simple static component with an array of objects to be used to create routes and links in child components:
I wasn't sure the best way to handle the
linksarray. I used it in a hook, obviously, but that seems like overkill since I'm never changing it (hence why there's nosetLinksfunction being pulled out ofuseState). But I was wondering, if I use it as a local variable,const links = [{ path . . . }];won't it get recreated every time the app renders?Would it be better to make this a global variable (tends to be a bad idea), or a local variable, or continue using it in state?
1
u/wefrick Apr 15 '19
My question is related to react-router-dom / BrowserRouter:
I am making a react web app with create-react-app which I intend to host as a static page (backend API from Firebase). I use the BrowserRouter and in the development mode this works just fine - if the app is on a route which is not the home and I refresh the page in the browser, the route is refreshed.
When I make a build for production, host it (with serve) from my computer, and refresh the app while being on a route (localhost:3000/someotherroute) and refresh the page, I get a 404, page not found.
Is this an issue with serve or did I get something completely wrong and the BrowserRouter doesn't work if the app is hosted as a static page?
Thanks for your help!
1
u/richard_h87 Apr 15 '19
Hi!
Sprikled around hooks and general react programming, people are talking about references that will/won't change... What does that mean for my component? For example useReducer... Will react skip rendering if the objects returned from hooks reference doesn't change?
1
u/[deleted] Apr 15 '19
I'm pretty new to React, so there are a few things I would like to ask:
It would be nice if you guys can recommend me some public repos that do well the two things above so I can learn from their coding styles. A small-sized or medium-sized repo would be better since I'm not really confident in my code reading ability.
Thanks a lot!
1
u/argiebrah Apr 15 '19
When you use react router, when user enters a certain url inside the router, does it loads only the router exact path or does it load resources from other pages? If it only load from the current page, how does it works?
1
u/rustybluz Apr 15 '19
I am doing my first react app. I am doing a To Do app, I got a checkbox to render a line through when clicked, only it does that to the whole list. Now I am toggling a property in state to put the line-through. How do I cross out only the item clicked?
https://codepen.io/yossiherz/pen/wZqwpB
1
u/Unchart3disOP Apr 15 '19
I am working on my first react app atm, but I'd like to add some effects to it so it's abit more dynamic. The app I am working on atm is a website that emulates twitter with profiles having tweets and all that stuff but whenever I delete a tweet -or load the page in general- the tweets just are there I'd like to add a more gliding effect to them so that they almost like slide from top to bottom if that makes any sense but I am not sure which libraries to use for it? I have looked up React Spring in the past but it was just too difficult for me to grasp? are they any other alternatives or should I get more into React Spring
Thanks
1
u/fpuen Apr 16 '19
How do I use .createElement() to render child components like <Child1 yes={true} /> and <Child2 func={props.func} /> without JSX?
It wouldn't be a string. I could see it being a variable, but then I think I'd need an array to have more than 1, so maybe:
Hmm. Couldn't get the child props in there. How's it done?
1
u/themantalope Apr 16 '19
Hi everyone! Super noob question, but hoping someone can provide some guidance.
I've been working on a webapp for a bit now, and I'm very happy overall with the development. I've used bulma as my css framework, and the pages render nicely in all the mobile browsers (chrome, firefox, safari, both iOS and Android when applicable) I've tested it in. Bulma is nice as there are easy to use breakpoints for various screen sizes, and most of the breakpoints are handled in css.
I've just started to research react and react-native, and I came across the react-native-webview project. If I understand this correctly, am I able to set up a react-native-webview interface, point it at my url and serve my app? If so that would be amazing because (I hope) I would not have to completely re-write the interface (I used flask/jinja with css, html and some custom js). Additionally my understanding is that using react-native I could cache many of the pages on the user's local drive, which would give the app some functionality when the user is off-line.
Are my assumptions about what I could do with react-native and the react-native-webview project correct?
1
u/LudekSt Apr 16 '19
Hi, I'm trying to integrate APIs that accept different types of Refs: ref objects vs callbacks. I have developed this hybrid ref handler. I can't see any obvious problems, is there any catch?
Inspiration: https://github.com/facebook/react/blob/master/packages/react/src/ReactCreateRef.js
1
u/ZeusAllMighty11 Apr 16 '19
What are people using now for animations (including mounting/unmounting) for components?
I tried react-transitions-group and react-spring and I see there's pose and a bunch of other libraries out there.. I want to like react-spring but it just doesn't work for me sometimes and there aren't enough examples online using for me to figure out what I'm doing wrong.
1
u/Pasgoyf Apr 16 '19
If I switch it from the /catalog/card-names to the /cards line, the code breaks, saying something about "Objects are not valid as a React child". I think it's because the way the JSON file is made, as in it's not just a list of card names. How can I use the same code but change it so it spits out, say, the oracle_id value of each one?
Also are there any major problems with this code? I've been experimenting with different ways of printing a mapped list into HTML and this is one of the shortest ways I've seen of doing it.
1
u/30thnight Apr 17 '19
Does anyone have great examples of marketing site built with React?
This might be a wishful request but it would really cool to see a git repo.
1
u/financial_azaadi Apr 18 '19
I have started studying HTML and CSS a week back. Can someone please tell me the learning path up to React? Thanks in Advance
1
u/thedobowobo Apr 18 '19
Started working on a React Project about a month ago and have hit a bit of a wall with the JSX syntax. I'm rendering a dropdown of li elements inside a modal so a user can switch between modals within the modal itself. The list is rendered when it's clicked:
However I have a bug with firefox where that ul is shown as whitespace below the dropdown button. That ul should only be rendering when the `showNotamModal` is true - i.e. when it's been clicked. So I need it to be opening and closing the tags within that conditional, but syntactically it doesn't seem to work. How can I render these tags here? I've tried closing and reopening curly braces but no luck. Thanks in advance,
1
u/maulanakmal Apr 19 '19
How is the normal / de facto way to save access token that returned from the back end to be used with subsequent API request in React? Currently i think it is to save it in cookies or local storage. but i am not sure because i just started doing react.
1
u/D1gitalConversion111 Apr 19 '19
I hit a stumbling block trying to configure my environment (dotenv.config). Stack overflow wasn't able to help me mainly because my .env file is already in the root server folder of my twitter clone.
Here is my code:
>const express = require('express');
>const dotenv = require('dotenv').config({ path: '.env' });
>const mongoose = require('mongoose');
>//setup environment
>dotenv.config;
>//mongo db connect
>mongoose.connect(process.env.MONGODB_URL, { useNewUrlparser: true });
>const app = express();
>//run app
>const PORT = process.env.PORT || 5000;
>app.listen(PORT, () => console.log(`server running on port ${PORT}`));
>const express = require('express');
>const dotenv = require('dotenv').config({ path: '.env' });
>const mongoose = require('mongoose');
>//setup environment
>console.log(dotenv.parsed);
>//mongo db connect
>mongoose.connect(process.env.MONGODB_URL, { useNewUrlparser: true });
>const app = express();
>//run app
>const PORT = process.env.PORT || 5000;
>app.listen(PORT, () => console.log(`server running on port ${PORT}`));
Here is my .env file:
>PORT=5000
>MONGDB_URL=mongodb://localhost/tweeters
>SECRET=runningSec
I can't figure out why my dotenv.config() function isn't found.
Suggestions appreciated.
1
u/Bulbasaur2015 Apr 20 '19
whats the best way to insert a favicon in react? is it react helmet?
1
u/KSeanJBz Apr 20 '19
I am using fabric.js and using fontawesome metadata icon to create icons on canvas nodes. However on initial load the icons do not appear unless i interact with them.
My question is how do I load the fontawesome css first so that the unicode will be recognized on initial load in react?
1
u/Kyrthis Apr 21 '19 edited Apr 21 '19
tl;dr: Why use functional components with hooks in the case when you effectively need class methods?
I was watching this tutorial on using Hooks, and a thought occurred to me. Classes not only provide state by binding variables to
this, wherethisis the instance of the underlying JS Function object, but they also can define class methods, which I think are instantiated themselves and defined as belonging to the instance when the constructor is run (or as belonging to the module once Babel does its thing). To recreate this functionality using functional components with state hooks, we need to define functions or declare function expressions within the functional component. Doesn't that mean that we are re-instantiating those "member" functions upon every render?For an example, I've linked the tutorial's App.js code on Github. Specifically, I'm referring to the
upvoteCourseanddownvoteCoursedeclarations.Am I making too big a deal of this? In this case, the
<App/>is a top-level component, so re-renders will be limited. However, I thought one of the ideas of Hooks was to be able to provide state to much smaller components far lower on tree (kinda replacing Redux in small-to-medium applications).1
u/[deleted] Apr 21 '19
I'm a complete authentication novice. I've read about JWTs and managed to implement something a while a go, but I've no idea how I can use something like OAuth to use the GitHub APIs.
Am I able to do it without a server? How do I keep API keys secure? So much I don't understand. Any resources are much appreciated.
1
u/NoftScarlet Apr 21 '19
Hello everyone, I'm learning React now and I'm really confused about the parent-child structure:
Thank you very much.
reference: https://stackoverflow.com/questions/24939623/can-i-update-a-components-props-in-react-js
1
u/Pasgoyf Apr 22 '19
I'm working with hooks. How can I update the state when I type something into the input box in this code?
https://codesandbox.io/s/6x1xp57zmk
I'm pretty sure that it's not working because the rezCards function only fires when the app loads. How can I change that so it triggers with the onChange of the input field also?
1
u/OrangeDrangon Apr 22 '19 edited Apr 22 '19
I have been working with React for the first time and have constructed a basic todo app (boring I know), anyway when I went to start implementing tests I started getting this error:
console.error node_modules/react-dom/cjs/react-dom.development.js:506Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates amemory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanupfunction.in Table (at Root.component.tsx:10)in div (at Root.component.tsx:9)in Root (at Root.test.tsx:10)The code! The website!
Sorry I am very new to react and don't know how to fix this!
1
u/NickEmpetvee Apr 23 '19 edited Apr 23 '19
React Router has me racking my brains. I have some public and private routes defined in my top-level App.js. In nested class components, I'd like to make use of those routes. Would be grateful for anyone who can advise on the best way to do this. It seems inefficient and redundant to recreate the routes in a lower component, but if that's the right way to make it happen I'm game. I'm thinking that there may be a better way though, perhaps by passing routes down as props and linked to in the nested component?
NOTE: not looking to implement nested routes (unless that's the way to solve for the need). Ultimately, I'd like to have links in my nested components that can trigger routing from the top level.
NOTE 2: I have a PrivateRoute component at the top level that prevents access to certain links unless properly credentialed.
1
u/[deleted] Apr 23 '19
I learned React, MERN, and React-Native with Redux on Udemy last year before Hooks were introduced.
1
u/OrangeDrangon Apr 25 '19
Hello I am back again with a problem with some of the more advanced hooks. I am attempting to use the useCallback hook to have the function not change and thus be not be recalled (with useEffect in children) but I am struggling to use useCallback to have constant functions from an array. What is happening is anytime the state in app changes the individual playlist data is being re-fetched. I believe the problem is where I use the map to dynamically make the Playlist components in Playlists...
code website (a spotify account is required to see the behavior sorry...)
1
u/Unchart3disOP Apr 25 '19
Which global state managment tool do you use and based on what? I have been using Redux on the current project I am working on and I took quite abit of time to get used and even till now Its not the easiest of things to handle. Now I have discovered some new stuff that could be a good alternative like MobX and ContextAPI so my question is when do you which of these libraries
1
u/HyperLathe Apr 25 '19
Hi! I'm wanting to get my head around React, and I thought recoding my portfolio website would be a good starting point. It's pretty basic static site built in PHP with some Ajax thrown in. (It's hyperlathe.com if anyone is interested in taking a look).
I've fired up an instance of create-react-app and started to go through a couple of tutorials. I guess my question is; for a site like mine, how would you approach breaking it down?
I'm guessing I'd divide each page and element up into constituent components and use react-router? I'm thinking of feeding in the static content via a single .json file for neatness...and I'm a big fan of sass...but beyond that, I'm struggling to figure out what first step(s) I should take.
I'm also aware that using React for a static site like this might well be overkill...but I'm treating it as a sandbox, I suppose...so any pointers or recommendations would be appreciated. :-)
1
u/trappedin00 Apr 26 '19
Hello. I'm going to be straightforward, I suck at web-design and I need to finish a project in 1.5 months for my university (also I ended up in a group with no designers). Everytime I try to give it a shot I finish up dropping it because I can't make things works and I just can't understand interfaces libraries. Can someone give me an advice please, specially in how to use templates, layouts, etc.
1
u/Money_Macaroon Apr 26 '19
Anyone here taken Wes Bos' Advanced React & GraphQL course? Is it worth the money?
1
u/JavascriptFanboy Apr 26 '19
I'm struggling to understand the purpose of "useCallback". It seems that I can achieve pretty much the same with "useEffect", hence, I'm not understanding the underlying finese. Can anyone ELI5?