I'm looking for help isolating out components from my body of code. I can't figure out how to link the input and output variables that are currently integrated throughout the app code. I've tried pulling out short parts of rendered html(/jsx) and helper functions, but so far no luck. (this is a requirement for a training program.)
My approach has been to cut and paste the desired segment into a new javascript file, replace in the app function with a component call to the new js file (via exporting from component, importing in app), replace the object variable in the component with a simple abstract name (e.g., change "task" to "object") and establish equivilancies in the component call. However, I can't get this to work -- when I remove the original variables and replace with component calls, everything else stops recognizing their variables.
So I'm looking for advice and help on how to make components of the sections detailed below. Sorry if this is vague without the specific error messages and an entire detailing of my approaches so far -- I figure there is something I'm fundamentally missing about how to isolate components from the code I currently have -- All the information I've found that should be relevant relies on props to be attached to property variables in the app component, which is not how I have my app coded. I'm hoping I don't have to gut my code and start over.
To begin with, this is the smallest contained code, the basic content of the html:
//ListItem
<li
key={listItem.index}
onClick={() => {
handleClick(listItem.index);
}}
> {listItem.string}
</li>
after that would be its container element:
//Div
<div>
<h2>w/e</h2>
<ul>
{list
.map((item, index) => ({ ...item, index }))
.filter((item) => item.position === "right")
.map((listItem) => (
<ListItem props.../> // the ListItem component defined before
))}
</ul>
</div>
so that finally, i would have:
<body><Div props... /></body>
the last thing I'm trying to seperate as a component is an object array being used to set state via useState:
//Tasks
//const [list, setList] = useState(
[
{ string: "string", position: "position" } //and many more
]);
For each piece of the code that you extract, ask yourself "what information does this code need to render?" The answer to that question becomes your props. A ListItem needs key, onClick, and its contents. You can pass the contents as a string property, or you can make use of props.children.
Not every single JSX element needs to be its own component. Think about which chunks of code change depending on the variables of your app. Those variables become props and those code chunks become components.
Related
tldr: New to frontend. Trying to include custom components within p-tags for a website, I've tried various methods but can't seem to get it to work unless I hard code the content into the return bit in my react component - this isn't viable as I would like to have many p-tags which would change on my website when a user presses next.
Hi everyone! I'm new to front end programming, and this is my very first question, so please excuse any incorrect terminology and/or question formatting!
I'm currently working on a react project where I have created custom components to include in my webpage. These components work when placed between p-tags.
For example, I made a custom component and it works as expected when I do something like:
function test{
return(
<p>Hello! This is a <ShowDefinition word="website"/> which I made using react! </p>
)}
However, I intend to have lots of content which would change using an incremental index, so I've placed my content in a separate jsx file to store as a dictionary.
I found that when doing something like this:
function test{
return(
<div>{script[index].content}</div>
)};
where
script[index].content = '<p>Hello! This is a <ShowDefinition word="website"/> which I made using react! </p>';
it just shows up as a string literal on the webpage. I've tried to wrap my string in {} but this did not seem to work.
I've also tried dangerouslySetInnerHTML with a dompurification to sanitise the html code
dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(script[index].content)}};
This worked however it excluded all of my custom components. So for the example sentence it would show up on the page as "Hello! This is a which I made using react!"
I understand now this doesn't work because dangerouslySetInnerHTML cannot convert custom components/only accepts html, however I am now at a complete lost as to what to do.
I have thought of storing the content in a md file then parsing it however I have little knowledge of md files/md parsers and from what I've found I don't think solves my problem?
Any advice would be greatly appreciated.
Thank you so much.
Ok, so first of all, this is definitely not how you should think when playing with React. Even if this is technically possible with things like React.createElement or dangerouslySetInnerHTML, I suggest you look at this first. I will help you get the thinking in react.
However if I had to do this in React, I would probably use a custom hooks or any conditional logic to render my jsx.
codesandbox
import "./styles.css";
import React from "react";
const useContentFromIndex = (index) => {
return () => {
if (index === 0) return <p> Index 0 </p>;
if (index === 1) return <p> Index 1 </p>;
return <p> Index 2 </p>;
};
};
export default function App({ index = 0 }) {
const CustomContent = useContentFromIndex(index);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<CustomContent />
</div>
);
}
Will conditional rendering out of an object code split and lazy load as expected? Here's a short example of what I'm talking about.
const Component1 = lazy(() => import('some path'));
const Component2 = lazy(() => import('some path'));
const Component3 = lazy(() => import('some path'));
render () {
const { selectionIndex } = this.state;
<Suspense fallback={<div>Loading...</div>}>
{{
one: <Component1 />,
two: <Component2 />,
three: <Component3 />,
}[selectionIndex]}
</Suspense>
}
I want to know whether all three components will load on render, or just the one selected by selectionIndex. I'm trying to use this to conditionally select something to display based on a menu set by state, but I don't want to load everything at once.
They will not get rendered all at once. You can experiment by yourself, put console.log inside components is an easy way to find out.
React for web consists of two libs, "react" and "react-dom". "react" is in charge of encapsulating your logic intention into declarative data structures, while "react-dom" consumes these data structures and handles the actual "rendering" part of job.
The JSX element creation syntax <Component {…props} /> translates to plain JS as an API call to React.createElement(Component, props). The return value of this API call is actually just a plain object of certain shape that roughly looks like:
{
type: Component,
props: props
}
This is the aforementioned "declarative data structure". You can inspect it in console.
As you can see, calling React.createElement just return such data structure, it will not directly call the .render() method or functional component’s function body. The data structure is submitted to "react-dom" lib to be eventually "rendered".
So your example code just create those data structures, but the related component will not be rendered.
seems like its conditionally loaded based on selectionIndex. all the other components are not loaded at once.
P.S.: if you ever feel like which will get load first, just put a console log in that component and debug easily
conditionally load demo link - if you open this, the components are being loaded initially based on selectionIndex value being "one".
I'm not going to go into too much technical detail, because I feel like #hackape already provided you with a great answer as to why, point of my answer is just to explain how (to check it)
In general, I'd recommend you to download download the React Developer Tools
chrome link
firefox link
and then you can check which components are being rendered if you open the components tab inside your developer console. Here's a sandboxed example, best way to find out is to test it yourself afterall :-)
As you can see in the developer tools (bottom right), only the currently set element is being rendered
Here is a simple example:
<script>
import Button from './Button.svelte';
let text = 'Click me!';
let sayHello = () => alert('Hello!');
</script>
<Button {text} {sayHello}/>
<Button {text} {sayHello}/>
<Button {text} {sayHello}/>
And if I get it right, since there can be lots of <Button {text} {sayHello}/>, it'll be nice to omit props passing somehow
And here comes Context API:
<script>
import Button from './Button.svelte';
import { setContext } from 'svelte';
import { text, sayHello } from './data.js';
setContext(text, 'Click me!');
setContext(sayHello, () => alert('Hello!'));
</script>
<Button/>
<Button/>
<Button/>
And somewhere in ./Button.svelte there are getContext() usage, etc
So, is the ability to omit similar props passing is the only reason to use Svelte's Context API?
So, is the ability to omit similar props passing is the only reason to use Svelte's Context API?
No, and, in my opinion, it is even not a very good usage of context.
The problem here is that you're obfuscating the data relationship between your parent component and its button children.
With props, it is explicit what data is needed by the button and where it comes from. On the other hand, with context, you only see one side of the relationship at once. In the parent, you don't see how the data is used (or even if it is still used at all). Same in the child, you don't see where it comes from.
Also, mistyping a prop, or removing one that is still needed for example, will result in an instantly visible dev warning (replete with the exact location of the problem). With context, you might end up with an undefined value that will produce weird runtime behaviour but will be hard to track down.
So, while saving a little bit of typing might seem like a good idea when you're in the process of coding and have everything fresh in your head, it actually increases the complexity of your code and might play tricks on you and give you a big headache later down the road... Not a good trade off if you want my opinion.
There are situations, however, where props are not an option. That is, when the data consumer component is not a direct child of the data provider component.
For example, you might have some kind of user session in your app. It will most likely be stored in a component near the root of your components tree (say, App), but it will be needed in components several levels of nesting deeper. For example, in a component displaying the user's name. Or somewhere else in a page, displaying some parts based on whether the user is authenticated or not.
You could pass by props through every components down the line, but this is kind of insane. This would tie all the intermediate components to data they're absolutely not concerned with.
So, in a case like this, context makes full sense. You would setContext in the App component, and can access it from just the components that need it.
Another example would be some kind of "composite" component, where you have a wrapping component (for example a form) and multiple components that can be used inside of it (for example inputs) and that depends on some settings in the container.
<Form>
<Input />
</Form>
Here, the Form component can't pass props to the Input component because the Input is not created directly in the Form component. It is fed to it by mean of a slot, and the Form can't see the content of this slot.
Still, Input is nested under Form in the resulting component tree, and so you can pass data between them through context.
To sum it up, context is really meant for situations where you can't use props. Either because it would be impracticable and lead to bad architecture, or because it is technically impossible (slots).
As an alternative to context, you could store the data in a dedicated JS module that both the provider and the consumer would access (e.g. import { setData, getData } from './data-source.js') BUT that would make your components singletons. This data could only be global. With context, on the other hand, you could have as many isolated data "scopes" as you need, one for each instance of the data provider component. In the Form example above, multiple <Form> components could coexist in your app at the same time, each having their own data in context. (They could even be nested inside each other and it would work.)
To conclude, here's a piece of advice. Context in Svelte is implemented with JS Map object, so you don't have to use raw strings as context keys. I generally use plain objects (or Symbol if you want to be fancy) that I export from something like a constants.js module. This largely mitigates the mistyping and IDE confusion issues I mentioned earlier.
constants.js
export const key = {name: 'my-context'}
Form.svelte
<script>
import { setContext } from 'svelte'
import { key } from './constants.js'
setContext(key, { ... })
</script>
<slot />
Input.svelte
<script>
import { getContext } from 'svelte'
import { key } from './constants.js'
const { ... } = getContext(key)
</script>
...
This eliminates any risk of context key collision you could have with a raw string. It turns mistyping back into a fail fast and crash noisily error (which is good). And it gives your IDE a far better clue as to what is happening in your code (an ES import can easily be parsed by dev tools, while strings are just random blobs to them), allowing it be far more helpful to you when you'll need to refactor that...
I have to display a long list with 2000+ entries. the list data changes dynamically in a way that for each second at least one new row will be added. The approach I am using is with react redux is
render (){
const listItems = this.state.listData.map((item, index) =>
<li key={index}>
<input value={item.name} /><input value={item.description}>
</li>
);
return (
<ul>{listItems}</ul>
);
}
so whenever store data changes it will change the data in component state which will rerun the render method. now there will be list of items generated in the virtual dom. react will compare this with actual rendered dom and just updates the only the new changes in the dom.
This is fine for UI rendering engine but what about javascript engine.
the problem I see is each time data changes the list of elements with 2000+ are recreated in javascript and compared to the dom snapshot. This is an unnecessary overloading considering javascript.
suppose if I am doing the same with javascript of jquery. it will be as simple as
socket.on('message', function(data){
store.push(data);
let listItem = $(`<li><input>${data.name}</input>
<input>${data.description}</input></li>`);
$('ul#main').append(listItem);
})
here a dom node is added on each time a message is received. this looks so simple with no overloading when compared to react way of doing. Is there is any better approach in react, redux that I fail to think. please let me know.
You are choosing a poor key identifier. Please use an key identifier to identify your message (record id/title), this will eliminate the changes to the dom.
Currently working on a react + redux project.
I'm also using normalizr to handle the data structure and reselect to gather the right data for the app components.
All seems to be working well.
I find myself in a situation where a leaf-like component needs data from the store, and thus I need to connect() the component to implement it.
As a simplified example, imagine the app is a book editing system with multiple users gathering feedback.
Book
Chapters
Chapter
Comments
Comments
Comments
At different levels of the app, users may contribute to the content and/or provide comments.
Consider I'm rendering a Chapter, it has content (and an author), and comments (each with their own content and author).
Currently I would connect() and reselect the chapter content based on the ID.
Because the database is normalised with normalizr, I'm really only getting the basic content fields of the chapter, and the user ID of the author.
To render the comments, I would use a connected component that can reselect the comments linked to the chapter, then render each comment component individually.
Again, because the database is normalised with normalizr, I really only get the basic content and the user ID of the comment author.
Now, to render something as simple as an author badge, I need to use another connected component to fetch the user details from the user ID I have (both when rendering the chapter author and for each individual comment author).
The component would be something simple like this:
#connect(
createSelector(
(state) => state.entities.get('users'),
(state,props) => props.id,
(users,id) => ( { user:users.get(id)})
)
)
class User extends Component {
render() {
const { user } = this.props
if (!user)
return null
return <div className='user'>
<Avatar name={`${user.first_name} ${user.last_name}`} size={24} round={true} />
</div>
}
}
User.propTypes = {
id : PropTypes.string.isRequired
}
export default User
And it seemingly works fine.
I've tried to do the opposite and de-normalise the data back at a higher level so that for example chapter data would embed the user data directly, rather than just the user ID, and pass it on directly to User – but that only seemed to just make really complicated selectors, and because my data is immutable, it just re-creates objects every time.
So, my question is, is having leaf-like component (like User above) connect() to the store to render a sign of anti-pattern?
Am I doing the right thing, or looking at this the wrong way?
I think your intuition is correct. Nothing wrong with connecting components at any level (including leaf nodes), as long as the API makes sense -- that is, given some props you can reason about the output of the component.
The notion of smart vs dumb components is a bit outdated. Rather, it is better to think about connected vs unconnected components. When considering whether you create a connected vs unconnected components, there are a few things to consider.
Module boundaries
If you divided your app into smaller modules, it is usually better to constrain their interactions to a small API surface. For example, say that users and comments are in separate modules, then I would say it makes more sense for <Comment> component to use a connected <User id={comment.userId}/> component rather than having it grab the user data out itself.
Single Responsibility Principle
A connected component that has too much responsibility is a code smell. For example, the <Comment> component's responsibility can be to grab comment data, and render it, and handle user interaction (with the comment) in the form of action dispatches. If it needs to handle grabbing user data, and handling interactions with user module, then it is doing too much. It is better to delegate related responsibilities to another connected component.
This is also known as the "fat-controller" problem.
Performance
By having a big connected component at the top that passes data down, it actually negatively impacts performance. This is because each state change will update the top-level reference, then each component will get re-rendered, and React will need to perform reconciliation for all the components.
Redux optimizes connected components by assuming they are pure (i.e. if prop references are the same, then skip re-render). If you connect the leaf nodes, then a change in state will only re-render affected leaf nodes -- skipping a lot of reconciliation. This can be seen in action here: https://github.com/mweststrate/redux-todomvc/blob/master/components/TodoItem.js
Reuse and testability
The last thing I want to mention is reuse and testing. A connected component is not reusable if you need to 1) connect it to another part of the state atom, 2) pass in the data directly (e.g. I already have user data, so I just want a pure render). In the same token, connected components are harder to test because you need to setup their environment first before you can render them (e.g. create store, pass store to <Provider>, etc.).
This problem can be mitigated by exporting both connected and unconnected components in places where they make sense.
export const Comment = ({ comment }) => (
<p>
<User id={comment.userId}/>
{ comment.text }
</p>
)
export default connect((state, props) => ({
comment: state.comments[props.id]
}))(Comment)
// later on...
import Comment, { Comment as Unconnected } from './comment'
I agree with #Kevin He's answer that it's not really an anti-pattern, but there are usually better approaches that make your data flow easier to trace.
To accomplish what you're going for without connecting your leaf-like components, you can adjust your selectors to fetch more complete sets of data. For instance, for your <Chapter/> container component, you could use the following:
export const createChapterDataSelector = () => {
const chapterCommentsSelector = createSelector(
(state) => state.entities.get('comments'),
(state, props) => props.id,
(comments, chapterId) => comments.filter((comment) => comment.get('chapterID') === chapterId)
)
return createSelector(
(state, props) => state.entities.getIn(['chapters', props.id]),
(state) => state.entities.get('users'),
chapterCommentsSelector,
(chapter, users, chapterComments) => I.Map({
title: chapter.get('title'),
content: chapter.get('content')
author: users.get(chapter.get('author')),
comments: chapterComments.map((comment) => I.Map({
content: comment.get('content')
author: users.get(comment.get('author'))
}))
})
)
}
This example uses a function that returns a selector specifically for a given Chapter ID so that each <Chapter /> component gets its own memoized selector, in case you have more than one. (Multiple different <Chapter /> components sharing the same selector would wreck the memoization). I've also split chapterCommentsSelector into a separate reselect selector so that it will be memoized, because it transforms (filters, in this case) the data from the state.
In your <Chapter /> component, you can call createChapterDataSelector(), which will give you a selector that provides an Immutable Map containing all of the data you'll need for that <Chapter /> and all of its descendants. Then you can simply pass the props down normally.
Two major benefits of passing props the normal React way are traceable data flow and component reusability. A <Comment /> component that gets passed 'content', 'authorName', and 'authorAvatar' props to render is easy to understand and use. You can use that anywhere in your app that you want to display a comment. Imagine that your app shows a preview of a comment as it's being written. With a "dumb" component, this is trivial. But if your component requires a matching entity in your Redux store, that's a problem because that comment may not exist in the store yet if it's still being written.
However, there may come a time when it makes more sense to connect() components farther down the line. One strong case for this would be if you find that you're passing a ton of props through middle-man components that don't need them, just to get them to their final destination.
From the Redux docs:
Try to keep your presentation components separate. Create container
components by connecting them when it’s convenient. Whenever you feel
like you’re duplicating code in parent components to provide data for
same kinds of children, time to extract a container. Generally as soon
as you feel a parent knows too much about “personal” data or actions
of its children, time to extract a container. In general, try to find
a balance between understandable data flow and areas of responsibility
with your components.
The recommended approach seems to be to start with fewer connected container components, and then only extract more containers when you need to.
Redux suggests that you only connect your upper-level containers to the store. You can pass every props you want for leaves from containers. In this way, it is more easier to trace the data flow.
This is just a personal preference thing, there is nothing wrong to connect leaf-like component to the store, it just adds some complexity to your data flow, thus increase the difficulty to debug.
If you find out that in your app, it is much easier to connect a leaf-like component to the store, then I suggest do it. But it shouldn't happen very often.