Hi! You can use Hooks instead of Classes.
"Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class."
https://reactjs.org/docs/hooks-intro.html
Why use it? From the documentation itself.
"It’s hard to reuse stateful logic between components."
"Complex components become hard to understand."
"Classes confuse both people and machines."
If you have some data that needs to be shared between a parent component and multiple child components, a good option is using react context
This way you can keep the data in one place but allow multiple child components to access it anywhere in the subtree.
Alternatively, you could define some constants in an entirely separate file and import that data into each component. This would be useful if you don't really need the data to be dynamic during runtime. Environment variables are usually stored this way in my experience
Separating your pages into separate components, like you're currently doing, is good practice. You don't want components to get too large to maintain, and making smaller portable components will be much more useful later on as the project scale grows.
I’ve seen this done for sure in projects where you want to share some global state with specific components but don’t want to clutter up the components too much by passing props around all over the place.
That being said, you may want to take a look at React Context as well. Context is one option for doing exactly what it seems like you are trying to do.
This should help: https://reactjs.org/docs/state-and-lifecycle.html
In react never change props directly, so this this.props.posts.unshift(test)
is wrong, and don't mutate arrays or objects, how to avoid mutation - depends on the case, usually destructuring helps, sometimes you need "filter" method
You’re trying to use this.setState() in a function component. Function components do not have a ‘this’ instance. Please read the docs https://reactjs.org/docs/hooks-state.html and be careful when copy and pasting. Also you might want to learn about using a code formatter because your code is very messy and hard to read.
This should help you get started https://reactjs.org/docs/faq-ajax.html
if you're completely new to react start with tutorial on that site as well and get comfortable with react on its own before you start connecting it to other things.
that's actually the standard way to handle the situation, left alone solutions involving state management (not the right thing in this case, because the project is quite simple). In general, you want your state to be in the first component that contains all the components that are using that state. If I'm confusing you, sorry, feel free to ask for clarification. Anyway, I found useful the React doc itself, this page in particular
I would avoid Redux for the time being, React Context will more than likely get you to where you need to be, especially if you're using Hooks (there is a useContext Hook).
Here is a great intro to Hooks, and if you know JavaScript to some degree already, it should be easy enough to follow along with: https://reactjs.org/docs/hooks-overview.html
You can also YouTube a ton of "intro to React Hooks" videos.
A quick overview of what these things are:
Hopefully this helps get you started!
I usually use Axios to perform API calls. These can be placed in an effect hook (useEffect), which calls AFTER the DOM has been updated.
​
https://reactjs.org/docs/hooks-effect.html
​
But you can cram your API calls into an effect hook, and use the responses from these calls to set state within your component, thus triggering to conditionally render additional child components or altering the elements that are being rendered within the given component, itself.
>TypeScript
React has good typecript support, you can use this.
>MVVM
React is very low level, you have a component that accept props, does some things and renders
You can asely make an MVVM architecture.
for this, you can use the library redux, where you can basically throw actions from your components, and then "connect" to redux so you can render the latest data
>Dependency injection
I don't use this alot, but one of the great strengths of react is that it is relatively low level. You can even pass around components in props and inject things that way. React works the best with composition: https://reactjs.org/docs/composition-vs-inheritance.html
yea I did a udemy course that only taught class based components. I learned React hooks through the Official docs . It does a good job explaining each hook. The examples as well use functional components, which really is not a big change from class based components.
You could use Firebase Authentication. https://firebase.google.com/docs/auth
Not only can you authenticate an email and password, you can also use Facebook, Google, Twitter, Github, you can also use phone number, anonymous login. You can also have custom authentication.
Don't use a onClick function in a <li/> tag, this isn't a good practice. Instead go for a <button /> inside your <li/>.
You can see a example here: https://codesandbox.io/s/reddit-li-list-example-91rkj?file=/src/App.js
Well you can just run npx create-react-app my-project-name
to get your boilerplate set up (will download all the files and give you a basic, empty project you can start with, with all config etc done for you). Then just run npm run start
to get it running on localhost in your browser with hot reloading and all that jazz.
The biggest issue I see is that the best way to learn is through either the docs (make sure you learn the Hooks version not the older Class based version), youtube can help a lot, I never did any online courses but those are available too.
I guess you could just download / screenshot / copy paste docs into some offline word doc / dropbox paper / etc and use those? But the command I mentioned in my first para is all you need to actually USE React.
EDIT: I should add, in case you don't have them, you will need to download and install Node.js and Node Package Manager (npm) as well.
React docs. https://reactjs.org/. Also, start simple. After you enter npx create-react-app you can do npm start and its deployed automatically in your default browser. From there, slowly remove what you dont need and add small steps at a time. and if you can do it with a hook, use a hook.
Interesting! Might have to try that next time I’m having such an issue, any tips? Is it also just a simple component like on the react docs or did you build something custom?
You need to use reference to get access to component's native elements. But think twice before doing it, React's mindset is not to touch native elements. For your task you can use CSS-variables and change them in parent component.
And you are not setting the values correctly. Please follow the documentation on how to correctly set state values https://reactjs.org/docs/forms.html
You should have all those values filled before submit, not fill them on submit.
You should then check the Context Api from React doc
https://reactjs.org/docs/context.html
You can create a React context that can store multiple variables and function that can be called in every child component
If you want a small example :
// context.js
import React,{useContext} from "react"
const AppContext = React.createContext({
volume : 0,
updateVolume : ( volume ) => {}
})
export default AppContext
// App.jsx
import AppContext from "./context"
import React , {useContext,useState} from "react"
export default function App (){
const [volume,setVolume] = useState(0)
<AppContext.Provider values={{volume, updateVolume : setVolume}>
{ /* Your react app */}
</AppContext.Provider>
}
// Component.jsx
import AppContext from "./context"
import React,{useContext} from "react"
export default function Component(){
const {volume , updateVolume} = useContext(AppContext)
// Your component , now you can use updateVolume as a normal function
}
createRoot enables concurrent mode, which allows React apps to be more fluid and non-render blocking. https://reactjs.org/docs/concurrent-mode-intro.html
They are likely keeping the render API to not break existing apps built on < React 17
In any case, follow the advice from react team. Don't overthink it and just choose something you feel comfortable to work with. Take in account that you could work with your own folder structure. Each person/team/project is different and you must know better than anyone what adjust better for it.
Check my answer to rohitsuri. The "issue" is explained in the react documentations, under "Booleans, Null and Undefined are ignored".
I used two different contexts, one for the state and one the dispatch because it causes less rerenders.
From the documentation: "In large component trees, an alternative we recommend is to pass down a dispatch function from useReducer via context... ...If you use context to pass down the state too, use two different context types — the dispatch context never changes, so components that read it don’t need to rerender unless they also need the application state."
You can find more about it on the following link: https://reactjs.org/docs/hooks-faq.html#how-to-avoid-passing-callbacks-down
I initially did it because the state was only relevant (at the time) for that function and I didn't want to pollute the main app with state declarations.
BUT then I wanted to effect the state with other functions.
So yes, looking at the docs they refer to this as lifting state up:
https://reactjs.org/docs/lifting-state-up.html
I would suggest to start with the React documentation ( https://reactjs.org/docs/getting-started.html ). It is very crisp and easy to understand. They also provide with the tutorial in case you want to learn by making project.
Back in the day, I'd have said to look for local companies looking for some light development work. But now we have COVID. I did find this article https://www.freecodecamp.org/news/how-students-or-anyone-can-make-extra-money-through-software-freelancing-4c802c43d1a1/ which talks about ways to get into software freelancing.
Yes you definitely can.
Check this out
Passwordless sign up is also a good option. Theres quite a few benefits of passwordless vs email/password
(From firebase)
But it also depends on your use case
​
Good luck
It still took me more time trying to understand "abstract code explained in sentences" than writing my solution. And I still don't fully grok it. You're mixing up ID's and indexes and DOM id's (are you talking about button dom ids? your use of the word "target" tells me yes.. probably a bad idea and you should use the framework and use your own props).
Anyways: here is updating a singe property of an object in an array: https://codesandbox.io/s/amazing-darkness-9kold?file=/src/App.js
Of course, sumedh, no problem. First let me provide the codesandbox-url: https://codesandbox.io/s/optimistic-violet-2cunl
Now to answer your questions: well, I learn React's basic by applying an old project of mine and its back-end. There I used it. Now I didn't want to rewrite the back-end. But I agree, JWT is good and I will use it. But I'd do so, when I understand how to do all this, like persistence and all.
In the cookie I am storing a token. The token is generated every time a user logs in in a browser. It's a 64 bit long string of various characters.
I hope my answers were okay to understand. If not, please let me know.
Try pasting your code into this codesandbox link. If it works, then something is wrong your code. If it doesn't something is wrong with your path
What exactly do you mean by "membership page"?
I think that what you want to do is create a react interface that utilizes the Stripe API.
I'm not really sure which part of the process you are struggling with, so for a good react tutorial, I recommend this one.
>Packt will be publishing "React.js – Key Concepts"
.t3_y1z511._2FCtq-QzlfuN-SwVMUZMM3 {
--postTitle-VisitedLinkColor: #9b9b9b;
--postTitleLink-VisitedLinkColor: #9b9b9b;
--postBodyLink-VisitedLinkColor: #989898;
}
Hi Sir, Thanks for your reply. I'm glad to know you love to add your review on React.js – Key Concepts. Please could you help me with your email so that I can mail you the details and Linkedin ( for connection).
Eligibility Criteria : Please note that in order to post a review on the book, you will need to own an account on Amazon com along with the eligibility criteria of a purchase history worth of 50 USD in the last 12 months. We would look for your feedback on Amazon in the next 15 days. Also, we might share the content in the current format (Word) as of now, but we promise to also share the final digital copy of the book with you.
Please share the email I'd for the eBook if you meet the criteria of posting reviewing on Amazon com, we will share the free ebook for you to review
Here is my LinkedIn ID for your reference:
https://www.linkedin.com/in/royluis-rodrigues-66479123/
This book will be published on Amazon by this month.
Regards,
Royluis
Expect unexpected bugs! React sometimes works in mysterious ways but thankfully the community has some great minds who create great content like Kent C. Dodds
Also, remember to eventually read the React Cookbook and get familiar with at least one Framework like NextJS or Remix (React is a library)
I made a digital boardgame using React Native:
https://play.google.com/store/apps/details?id=eu.fware.quetzal.android.free
It is basically my business card and the game I play the most with my friends and family.
I learned soooooo many things developing this project.
>u/reditn00b I have severe ADHD and learn way better through books, I found these older books that were fantastic for learning, and most of it was coding along with the book, and taught most of the concepts mentioned. I learned i learn differently than other people, and books a very key piece to my success in learning. Build your skills in the best way you know how and once you are ready start making projects on github, make things that are exciting to you! I wish you the best success!
>
>https://www.amazon.com/Head-First-JavaScript-Programming-Brain-Friendly/dp/144934013X
Get this book React 17 Design Patterns and Best Practices: Design, build, and deploy production-ready web applications using industry-standard practices, 3rd Edition https://www.amazon.com/dp/1800560443/ref=cm_sw_r_cp_api_glt_i_G26W96T8NFK8DNDG43TC
So say I had a questionnaire with a question component that simply contains a textarea for the question and several more for the answers. In addition the component also has a video player which needs to be displayed and hidden on the click of a button. Here is some code for the question component with the relevant section highlighted: https://hastebin.com/ixixacujop.js
You might want to look into Next js. It's an amazing framework for creating SSR and isomorphic web applications. Also, it has automatic static optimization, which is a game-changer IMO.
Hey,
Given you are using Firebase, I guess the product you are looking for is Firebase Cloud Messaging https://firebase.google.com/docs/cloud-messaging.
It lets you send notifications to your clients on web/mobile on specific times and for specific things (ie, different polls like you shared).
I hope that helps!
Why are you returning props.changeSurchargeFee(totalSurcharge) from your useEffect?
Besides, can't you just make a codesandbox with the problematic code? It'd be easier to follow your example.
you can use CSS variables for that.
I wrote an example here: CodeSandbox
What's basically happening is that you define a variable (--row-color-on-hover
) in your table's style
and access it in CSS via var(--row-color-on-hover)
You can also define a default value for that variable in your CSS by applying the variable to body
for example.
here is a working demo: https://codesandbox.io/s/jsx-in-state-weirdness-rku9f?file=/src/App.tsx
By setting state I mean setting state, and what you did instead?
It's not async. count
is a local constant to your App
function, which was set when useState
was called, it won't change during the current App()
call.
When React refreshes, it will call App()
again, that will call useState()
, you want to log your count
value at this point. In short: console.log()
should be called in the App()
body.
For cleanliness, you can wrap your hooks in a higher-order function for debugging purposes:
function withLog(hook) {
return (...args) => { // returns a function
const value = hook(...args) // this function will call the original hook, with the passed arguments
console.log(value) // then it will log the result of this hook's call
return value // and return this result to your main flow
}
}
And then use either react base State hook, or your wrapped one based on configuration:
import { useState as state } from "react";
import dotenv from "dotenv";
dotenv.config();
export const useState =
process.env.APP_ENV === "development" ? withLog(state) : state;
function withLog(hook) {
return (...args) => {
const value = hook(...args);
console.log(value);
return value;
};
}
Then you'd only have to change one environment variable to switch your hooks from production to debug mode, and won't forget any console.log in the code.
Here's the link of the full version: https://codesandbox.io/s/react-hook-with-logger-iqyte?file=/src/hooks.js
Hey u/kuldeep25oct so the bracelets are used when you are importing named functions.
So if you have 10 functions which you want to import in another file then you can import them all together and skip importing them one by one, assuming your functions are named exported.
Now if you import something without bracelets it means that you are importing default export function which can only occur once in a file. This is usually used when you are importing components etc...
I have drafted an example with both named and default exports so you can check it here: https://codesandbox.io/s/eloquent-lovelace-48yyp?file=/src/App.js.
Simple way to explain it is that hooks can simply cover all cases that class component can. People use it more because it provides more flexibility in testing and re-using code.
In class component you have all kind of life cycles and each one have different function for it where in functional component you can do it all with just one hook (useEffect).
I was thinking the same way as you do now when the hooks was introduced. I was thinking what is the point learning hooks when I can just write class component and achieve the same thing. Now after working for more then 2 years with hooks I would never again use class components as it's simply much easier to write functional ones. I feel like I can read the code easier as well.
So just give it a try and I'm sure you'll love it! Also if you already know class components then learning hooks should be really easy and it shouldn't take you much time. Generally it does the same thing but you just write it differently.
I have created class and functional component example where both of them do the same thing. I think functional component makes more sense and it might be easier for anyone reading the code better understand it. Check it here: https://codesandbox.io/s/quizzical-field-03fdy?file=/src/App.js.
I'm not an expert on react, but you could make use of props and useState. Like, maybe you can have something like
<SideBar currentTool={renderItem}/>
and a function called renderCalendar will change the state of the renderItem
and inside that component you can return certain component depending on the currentTool prop.
​
I made a code sandbox, I know it's awful and I just used if statments, but maybe this will give you a rough idea of how I would do it. Again, i'm not a react expert, in fact I started using it this month, but I'm having fun :D good luck and tell me if this is help.
​
https://codesandbox.io/s/for-the-reddit-guy-ytcfv?file=/src/App.js
Hey u/YourWlFEsBoyfriend it wouldn't be that easy to format the input field value as you always get the current value and if you try to change it then the appended text will be appended over and over again.
There is a package called react-text-mask
which does just what you want but it also has support for all kind of characters and for the currency one you can choose how many decimals, loading zeros etc... you want, so it's really useful in this situations.
I have drafted a small example so you can see it in work. You can find it here.
Are you calling setJobID?
As soon as you assign a state to a variable, it's value is preserved between renders. Even if you change them manually(aka jobID = 3), this won't do anything because react has not acknowledged that the state has changed.
​
I made this quick and simple example for you.
​
You'll realize that, every time you click the first button, a rerender happens(because we are forcing it by calling setAnotherState) and, even though, the "state" is changed manually to "hey" in the "doStuff" function; it gets reset to the default value every time.
​
The only way to change the state's value is through its setter fuction(setState) which is what happens if you click the second button.
​
React remembers the values inbetween renders and makes sure they are the same of either the last call to setState or the default value of the first call to useState.
I have drafted an example where you have a list with items and then if the list is longer then 10 we are rendering the show more button and loading new results.
I took comments and tried to make it as clean as possible so it should be easy for you to implement it in your example.
If you also want to have an icon which will switch to "Show more" once you hover over it then you should use React built in listener onHover, it shouldn't be tough at all. Let me know if you need help with that one too!
Example: https://codesandbox.io/s/wizardly-proskuriakova-00zl9?file=/src/App.js
Your second useState is not necessary in your code.
You could totally just use the props.text in your child element.
Because, when you create the state in your child component, it doesn't matter that the default value changes in consecutive rerenders. React won't replace the old default value for the new one. In order for React to recognize that the child state has changed, you need to call setState in your child(but that would be redundant).
​
Your case is probably more complex than what you showed here so maybe this could be useful to you:
If you really want to notify child components about a change in its Parent, there are a few ways you could go on about this.
​
One of which is using the observer pattern, through context hooks, and allowing child components to subscribe and unsubscribe from modifications made to the parent and then the child component becomes an observers who gets notified whenever something has changed.
I've made a quick example of such a pattern to another question, here in reddit, where a user wanted components to be notified whenever a user clicked a button on a global modal and those components were not necessarily childs.(link)
​
This, however, is a bit of over engineering for when you only have one child component and it is directly related to the parent.
You can still use the observer pattern tho, but you wouldn't create a context hook for that. You'd only send the subscribe and unsub methods through props.
​
Still; I can't think of a single reason not to just use the value props.text directly.
So I have a question I am struggling to get the tailwind to work in it, I will link my sandbox could you help me out.
https://codesandbox.io/s/autumn-monad-5b4tq?file=/src/components/HomeComponents/Navbar.js
I’m really sorry but the way the code is formatted in your post is making it really hard to debug where the potential error is.
Are you using a linter and/or prettier plugin for your code? A linter should be able to pinpoint where your problem is if it’s a syntax issue.
Two other options you can try:
Comment out all the code then slowly uncomment blocks until the error triggers, and debug from there.
Paste your code into a react codesanbox. There is a built in linter there that may help you pinpoint where the problem is.
The error message is directing you to what line it’s on, so looking at that line and making sure everything inside the template literal is correct would also be a good start.
React codesanbox link: https://codesandbox.io/embed/new?codemirror=1
howdy - put together a little code sandbox here
https://codesandbox.io/s/flot-jquery-react-rwrdd?file=/src/App.js
note that I added a script tag referencing jQuery in index.html. That makes jQuery available globally, which makes the import not break. I also added some local consts to reference the global jQ variables, because I think in class components some scoping stuff comes up from time to time? Can't remember exactly, but I had it in my code.
When you fire your handleRemove make sure your method asks for a argument. In this case you could pass the props.id. That way when it fires it passes its own id and allows you to find it to remove it.
You could also figure out a way by passing the event info but I was too lazy to go back and figure that out :)
Good luck to you hopefully this makes sense.
Example if you want. https://codesandbox.io/s/tender-darkness-bj47n?file=/src/App.js
You are right. I created a project now on Codesandbox. Because it's a lot of code, I didn't insert all, just what I hope is necessary. If it's not all you need, let me know (may answer in a few hours, may leave the keyboard later for a while, so no disrespect).
https://codesandbox.io/s/interesting-germain-33gp5?file=/src/project.contacted.js
I dont know if I understand what you what but I came with this idea:
https://codesandbox.io/s/bold-dream-r11yk?file=/src/App.js
It is a bad code, but since I didn't understand the problem I wanted to make the code as simplest as possible
Requirements:
Here is a code sandbox with the "Configuration" being a base URL and record count. There is a form to change the number of records. This will modify a web request (in this case, grabbing earthquakes from Quakelink). The requesting and parsing is handled in the DataFetcher, which will resolve that configuration with a fetch to a dataset. Finally, you pass the data set into a DataPresenter.
https://codesandbox.io/s/react-playground-forked-oeitk?file=/index.js
If this seems confusing or convoluted, then please take it on faith that this pattern will save you a lot of time, once you understand it.
Is your project using typescript? It looks like an object literal type definition, maybe for a destructured object
Typescript will be incredibly difficult to learn unless you are very experienced with JS first. TS is a superset of JS. But this is a good start.
https://www.typescriptlang.org/docs/handbook/typescript-from-scratch.html
If you’re trying to figure out why you’re seeing an extra one being added to guest only in the render, but not in the console, your culprit it React.StrictMode.
In the dev env, StrictMode double renders everything to help pinpoint problems in code (especially with hooks - see their docs for more details https://reactjs.org/docs/strict-mode.html).
Each <Cup /> is getting rendered twice, thus adding an additional 1 to the global variable. Your comment about not updating a global variable doesn’t need to be followed 100% of the time (it makes sense in some places), but fixing it wouldn’t have solved this issue.
If you remove StrictMode from the index.js file, your problem will go away.
Remember React.StrictMode as you move forward in your career. It plagued my team for over a 2 months when trying to use Apollo Graphql (fetch client) which was not tested in that environment and caused a lot of issues.
Right, but measurable impact does that have on the performance of a react app? Have you measured any performance indicators?
If not, you can start with the Profiler API to get some data.
Right, but how does that actually impact performance? Have you measured any common indicators of the performance of React apps?
If not, you can start getting some data using Perf.
I suggest that when the component realizes its props are wrong, instead of trying to render anyway or do nothing at all, it should render a warning of some sort.
if (propsAreWrong) {
return <span>{'your props are wrong. got xyz, expected abc'}</span>
}
// ... rest of your render method
Alternatively you could wrap it in an ErrorBoundary, actually throw the error in the render method and let the error-boundary render the warning
Should only be referencing DOM elements using refs in React. Say you have multiple instances of a component using the same ID on the same page. You will lose reference to the component/element you were targeting because there are multiples.
Have a read through the docs - they are very well written and will answer any questions you have.
This is a link to referencing elements in the DOM:
Define "slow". Is it slow during runtime (i.e. sluggish, lagging UI), or does it just take a long time to load?
In general, bundle size should not affect runtime performance, only load speed (which then again may or may not be a problem depending on what type of app we are talking about).
Improving runtime performance is not a trivial topic, but React's guide expands on it quite a lot: https://reactjs.org/docs/optimizing-performance.html
Improving load speed, on the other hand, is easy: look into reducing bundle size, or using code splitting as already mentioned to further reduce your initial bundle size (and thus initial load times). A 9 MB bundle is generally considered very large for common webapp types, although there are apps where it's normal to have even larger bundle sizes (typically frontend-heavy apps which are similar to native apps in their capabilities).
useEffect has good explanation in official documentation. All you need is to understand react component lifecycle and understand that react components are just plain JS functions without any magic (except for hooks, they are kind of magic) and they rerenders plenty of times.
Reject JSX become vanilla JS enjoyer! You can use the same tool that JSX uses under the hood: https://reactjs.org/docs/introducing-jsx.html#jsx-represents-objects
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
This may not be the cause of all of the additional renders, but if you're in development mode and rendering your app inside a React.StrictMode (create-react-app wraps your app in this automatically), your components will likely render twice so that React can detect certain problems and emit warnings.
It's useful if you need to do something outside of the react sandbox, such as updating the title of the page. The official docs can explain it better than I can probably: https://reactjs.org/docs/hooks-effect.html
Heyy just wanted to say that you may want to look into using React SyntheticEvent (https://reactjs.org/docs/events.html) which seem to be perhaps the latest evolution of how to best handle events. Lmk if you have more Qs
Oh, it is very likely i have no idea what I'm talking about or what I'm doing. This is where i got the idea from: https://reactjs.org/docs/hooks-faq.html#what-can-i-do-if-my-effect-dependencies-change-too-often
But after looking at it again, i see I'm not using it right anyway.
Component re-renders itself when any of 'useState' variables was changed, so "Parent" is re-rendered on both 'arr' and 'count' change.
Child components re-renders anytime when parent re-renders, unless it is wrapped with React.memo. And ff Child is wrapped, it won't re-render till it's props are shallowly equal or till inner state change.
Why react requires you to wrap it into React.memo, and don't do this by defaults? With React.memo it has to do additional work, also for React.memo work properly you would need to use "useCallback" for functions, and that's more work to do for react. So need to treat such optimizations carefully, as it's easy to make performance worse in this way.
Example 2 and 3 makes no sense, sorry, but Example 1 is fine to go!
Fighting re-renders may be a premature optimization, normally re-renders are harmless
To keep it fast I suggest to use a state manager, any of them should reduce re-renders
Directly from react: https://reactjs.org/docs/lists-and-keys.html#keys
You are seeing this because number.id
is undefined, been invalid prop for key.
Render props. Vue always leaves me wishing I could use render props.
Here is the first link in google auto suggest about react compound component. https://kentcdodds.com/blog/compound-components-with-react-hooks
The idea seems pretty basic if you understand context. Here is the react official docs for context: https://reactjs.org/docs/context.html
Basically you have a parent and some children. The parent will be the provider and the children would be the consumer. If you do it without provider, you have to cascade the props to every component until you hit the child. With the context api, you don’t have to explicitly cascade the props.
In terms of what do you setup on the provider and the consumer is up to you. Basically think of the values in provider as the same thing as state. You can have unidirectional or bi directional communication based on the methods you setup on the provider.
I strongly recommend reading the official documentation. This problem can be solved by composition https://reactjs.org/docs/composition-vs-inheritance.html
You should check out the React docs for this. They good job of explaining why you need keys and where to put them.
https://reactjs.org/docs/lists-and-keys.html
The short answer to your question is you need a key on the root element being returned in the array. In your example putting it on the div with the card-body class.
Here's some documentation on useReducer
--https://reactjs.org/docs/hooks-reference.html#usereducer
I agree with u/IGovnov that a state management library would make a lot of sense here, but if you're committed to hooks or that's just too much to chew on right now, useReducer
could be a good compromise.
JSX is compiled to vanilla js before it reaches the browser, so any JSX element like <li> is translated to React.createElement(), which is a valid js expression.
Use useState
https://reactjs.org/docs/hooks-state.html
On your LandingPageComponent create a state to hide or display your text field. Use a ternary to display the TextFieldComponent if true, and the ButtonComponent if false.To change showTextField value, you have to use the function setShowTextField. Because you want to have a child component to do it (ButtonComponent) you have to use props.
const LandingPageComponent = () => {
const [showTextField, setShowTextField] = useState(false)
return(
<div>
{showTextField ? <TextFieldComponent/> : <ButtonComponent setShowTextField={setShowTextField} />}
</div>
)
}
In ButtonComponent, you use props.setShowTextField() on a button with onClick. That will update the state of the parent (LandingPageComponent) and display the TextFieldComponent
const ButtonComponent = (props) => {
return(
<button onClick={() => props.setShowTextField(true)}>Click on me</button>
)
}
There are definitely guidelines: https://reactjs.org/docs/thinking-in-react.html
From your code, I'd say you're doing it right: Since App is the closest common ancestor of SearchBar and Results, this is the place to store the state they share.
Then, you still enforce that Single Responsibility Principle by passing the handler for your state as a callback to your SearchBar and calling it as a delegate.
However, I would say that you don't need to share the searchValue state and could keep it local to your SearchBar. Instead of the handleSearchValue, you pass the getDefaultItems as a callback, and define the handleSearchValue from your SearchBar component.
You can reuse your components for sure by rendering your app with renderToStaticMarkup() or renderToStaticNodeStream(). That would generate static HTML that you could then send into an email.
Just be careful with the HTML because most email clients are very picky on what they accept and it is a lot less than browsers, especially on CSS rules.
Can you elaborate on what exactly is better in function components?
According to react's documentation the usage of function or class components is not opinionated: https://reactjs.org/docs/components-and-props.html
So class components are not really legacy. To be honest I preferred using them in the past because you can arrange your code im multiple functions. Now I want to implement react-query and it looks like I have to convert my components which I don't really want to.
I really recommend reading the docs for hooks you can find them here.
Hooks allow you to update a piece of data that’s shared between multiple components. Changes to the data (hook) by one component updates that piece of data everywhere.
Take the users name. They change it in settings. The hook that you use to change the name triggers the state of the hook to be updated. This means the data changed. This triggers the user name to update wherever you’ve then implemented that hook.
You really should not do that. First, your MongoDB is not accessible from the outside of your local network, it will be terribly slow and your ISP most likely don't allow you to do that. They don't like residential customers taking unusual amount of traffic or let you open a huge security breach.
However, you can use a free tier Mongo Atlas with Heroku. Here is how to do it. It's not complicated and you might learn a thing or two about hosting 🙃.
Good luck!
I think you could do it by having the website look at the IP address or IP range that's accessing it. Then based on that it can allow access to the database or not. Or you could set up a login where once you're logged in you can access the database.
What you would need to do would be to either publicly host the server from your public IP or you could host MongoDB in the cloud (it's free and pretty easy to set up https://www.mongodb.com/cloud ).
This is so the website you're hosting on Heroku would have access to the database. It wouldn't be able to see if you were just hosting it on localhost and without a public IP address to access it through.
> why don't you create a "dev" MongoDB where you do modifications which can't be seen by the user?
As in use a Free Cloud Database for dev mode?
Yes I just wanted to know if it's doable
I tend to disagree. React is good because it manages by itself the common needs of frent-end apps under the hood. The downside of that is that you don't really see the full code that your browser will have to read, which is kind of the opposite you want when you're learning to code.
Also, React examples often assumes that you understand concepts like closures, differences between arrow function expression and named function and asynchronous code, which you probably won't have covered in 3 hours of JS basics...
If OP's goal is to create a website, a solid understanding of HTML and CSS fundamentals will be more helpful than any copy/pasted React app.
Otherwise, Free Code Camp seems to have solid resources about learning javascript advanced concepts and React / Redux. I advise to finish, at least, the ES6 and functional Javascript lessons. But the more time you spend on learning the fundamentals, the easier you'll grasp React and other frameworks!
NextJS is a framework built on top of React that provides a great many features. Primarily, Server Side Rendering (SSR) to improve SEO, load times, etc. (and many more)
To implement it, you would be required to start a brand new project and manually move all the code over. <Route>
s would turn into individual pages, etc.
If you're new to React, I would stick with what you know how to use. As you gain more experience, however, I'd take a closer look at NextJS and see if it'll help you.
All of my React projects use NextJS, just because of how great it is. For you, though, you may just want to stick with Create React App (CRA) for the time being.
my project imports firebase through a named initializeApp
import
import { initializeApp } from "firebase/app";
const firebaseConfig = {
apiKey: "some text",
authDomain: "some text",
projectId: "some text",
storageBucket: "some text",
messagingSenderId: "some text",
appId: "some text",
measurementId: "some text",
};
const firebaseApp = initializeApp(firebaseConfig);
I recommend using firebase realtime database. https://firebase.google.com/docs/database
It's a simple (and free) solution for your need to have data stored somewhere and access the data through API calls. There are a lot of tutorials on YouTube on how to use it with React.
I'm really confused as to why your code is not working, the only think i could think of is that your store is not getting or providing the right state, i made this codesandbox that simulates almost everything you are doing in your exept for your store config (i didn't find a photo of that code) but i hope this could help to see if something is wrong with that part.
https://codesandbox.io/s/hungry-microservice-tpjf9?file=/src/App.js
Yeah thats what i'm thinking. Also the way i'm managing state is probably poor as well with passing props to my modals - but that is another different concern entirely.
Here is the code on codesandbox:
https://codesandbox.io/s/youthful-shannon-jtr4k?file=/src/App.js
So the way i try to organize my routes is to create a component that has my "main" routes in side of a Switch and that component would be rendered in my app.js file and then try to have the nested routes inside of the components being rendered by the main ones.
So for your example i would create a main settings route that renders a component that has a Switch with some other routes in it and just like you said useRouteMatch is amazing here to make it a little more dynamic in case you changed your main route for some reason.
As far as your current problem, i don't think that is the case, because of the way route matching goes, it tries to read the route from left to right and find the route for you, so it would first go and try to find a match for the route in the first "main" switch and as long as you dont specify all tyour main routs as exact beside than your "/" then it should find a match in your "/settings" route and render that component and then this component has a Switch so it would hit that second Switch and tries to find a match and renders that component and so forth.
I made a codesandbox that make a smilar routing to the one you mentioned, you can check it at
https://codesandbox.io/s/hardcore-goldwasser-nmtlo?file=/src/App.js
It will render the EditProfile component even if you just type in /settings/editprofile in the url so if it might that you have some route that is marked as exact and because of it its not able to render the component that has the nested routes in it
I haven't tryied this library before but i installed it tried to make adjustment you needed and it seems that the Cursor component that they are using is not updating getting the cursorClassName value to be applied.
The Typing comonent accepts a cursor property that takes in a react component to show so you could make your own cursor and use it there.
Here is a CodeSandBox that i made to show the way it's working.
https://codesandbox.io/s/dazzling-silence-hzmvi?file=/src/App.js
https://codesandbox.io/s/peaceful-brattain-uho18?file=/src/index.js
And another sandbox to explain when ".then" being a microtask matters (it's done before the macrotask that's created before promise is resolved)
.then() microtask is only created when the promise gets resolved though. It can be 5 seconds from now. You aren't freezing all your queues because of a fetch.
https://codesandbox.io/s/nostalgic-browser-8thqi?file=/src/index.js
Here's a sandbox for your better understanding. Look at the code and at the console output.
Yeah I read your first comment, and that seems incorrect. You don't need useEffect to use the updated state. Component will rerender AFTER the state is already updated.
Sandbox here: https://codesandbox.io/s/pensive-dijkstra-dhm6g?file=/src/App.js
Tell me why would you need useEffect here because I don't see why
Thanks for the clear example!
It's similar to what I went with:
https://codesandbox.io/s/interactive-request-cancellation-ukyov?file=/src/App.js
I used a ref instead. I'm not a big fan of aborting a Promise. I'm not against anyone else using it though if it brings value to the code.
look at this sandbox I made.
https://codesandbox.io/s/react-playground-forked-4p6jv?file=/TickerDropdown.js
it looks like its working, but you should note that the way you are setting the state doesnt seem to match the shape of the object when you first useState({ symbols : [] }).
You are using a state of an object in the beginning and pushing an array setTickers(tickersOptions);.