I am following a tutorial and they set a static object named defaultprops and after setting it this.props could be used in the same component, Why is this possible, I mean what's the function of the static defaultProps and is it a bulit in function in React.
class TestComponent extends Component {
static defaultprops = {
food: ["goatmeat", "yam"]
}
render() {
let categories = this.props.defaultprops.food.map(foods => {
return <option key={foods}>{foods}</option>
});
let {test} = this.props;
return (
<p>
{this.props.test}
</p>
);
};
}
Default props are nice to not have to specify all of the props when passing them to a component. Just as the name implies, it allows you to set nice defaults for your props which will be used in the even that overriding values are not passed in. Please keep in mind that leaving out the prop will result in the default value being used, whereas passing in null will result in the null value to be used.
More info may be found here.
Edit
To answer the questions asked more explicitly:
This is possible because this is how React works. This is in-built functionality for programmer and logical convenience.
For the TestComponent in your example, imagine that it is used in another component. If you just use <TestComponent />, the component will have a food value of ["goatmeat","yam"]. However, you may always override this as you wish by passing in a different value for the prop when calling it. For example, you could use <TestComponent food={["cheese", "eggs", "cabbage"]}/>. This will result in this instance of the component having the food value of ["cheese", "eggs", "cabbage"].
I think it is also a good point to note that it should be defaultProps and not defaultprops because I am fairly certain capitalization matters but if anyone would like to correct me I would be happy to redact this point.
Related
Newbie here, I am studying the documentation of react and in React Context API, I couldn't understand something, I won't understand the rest of the subject if I don't understand it. Can anyone help me what does it mean through using an example?
The Toolbar component must take an extra "theme" prop
and pass it to the ThemedButton. This can become painful
if every single button in the app needs to know the theme
because it would have to be passed through all components.
class App extends React.Component {
render() {
return <Toolbar theme="dark" />;
}
}
function Toolbar(props) {
// The Toolbar component must take an extra "theme" prop
// and pass it to the ThemedButton. This can become painful
// if every single button in the app needs to know the theme
// because it would have to be passed through all components.
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}
class ThemedButton extends React.Component {
render() {
return <Button theme={this.props.theme} />;
}
}
The Toolbar component must take an extra "theme" prop
this can be like <Toolbar theme="dark">
and pass it to the ThemedButton
how Toolbar component pass this prop to ThemedButton? and kindly clarify the rest of the comment as well.
Thank you for any help? You are kind
In your Toolbar component, it takes a parameter props, props is whatever properties have been passed to it when calling it, as in <Toolbar param1="someString" param2={someVariable}>, in this case the props value in Toolbar will be an object with the data you passed as key=value like for example: {param1: "someString", param2: content_of_someVariable}
And if you don't actually use those props (properties)/parameters in Toolbar, but rather in a subcomponent, then you have to pass them again to another level, like in <ThemedButton theme={props.theme} />, then ThemedButton itself finally passes the value to the component that actually makes use of, which is in your case: <Button theme={this.props.theme} />;.
So you had to pass the theme across multiple components, which don't use it or care at all about it, just to get it through to the final Button component.
(answer ends here, below is my effort to explain context API in an easy way)
To avoid that annoying level to level to another..., you can use the context API. Because it is really incontinent to pass a value across 3-4+ levels/components every time you want to use it in the last one in the chain.
Think about the context like a variable defined and exported on a root level and holds some data (like the user login status for example, or the theme infomation), and whenever you require that data, you import it and use it directly. You use the Provider property of the context you define (MyContext.Provider) to assign the data to it, and you use the Consumer property (MyContext.Consumer) to consume/access that data you assigned in the provider.
The beauty of the context consumer, is that whenever the data is updated in the provider, the consumer immediately gets the new data and triggers a re-render with the new data.
I hope I explained it in a simple and clear way. Write a comment with any questions or unclear parts and I can try my best to improve the answer.
Best of luck!
Props are properties that help define the way your JSX appears on the page.
When you use a component that you have created, you can pass it props like below:
<MyComponent myProp={myPropValue} />
You can continue to pass props down through the component hierarchy as well. So say you have a component tree like below:
MyComponent
--MySubComponent
----MySubSubComponent
You can pass props from MyComponent to MySubSubComponent like so:
<MyComponent myProps={MyProps} />
<MySubComponent mySubProps={props.myProps} /> //Props are the value you gave in the parent component
<MySubSubComponent mySubSubProps={props.mySubProps} />
Whatever title you give the props when declaring the component in JSX is the title you will call to get the value of the prop like props.myProps
I am receiving props in my component. I want to add a property 'LegendPosition' with the props in this component. I am unable to do that. Please help me with this.
I have tried this code yet but no success:
var tempProps = this.props;
tempProps.legendPosition = 'right';
Object.preventExtensions(tempProps);
console.log(tempProps);
You can't modify this.props. Here tempProps is reference of this.props so it does not work. You should create a copy of the props using JSON.parse() and JSON.stringify()
var tempProps = JSON.parse(JSON.stringify(this.props));
tempProps.legendPosition = 'right';
Object.preventExtensions(tempProps);
console.log(tempProps);
For a better and efficient way to deep clone object see What is the most efficient way to deep clone an object in JavaScript?
props is not mutable, you cant "add" anything to them. if you want to "copy" them then you need to do
const tempProps = {...this.props};
And the only reason i can see you needing to add more props is to pass it down to a child, but you can do that without adding it to the props object.
EDIT: add props with extra prop
<Component {...this.props} legendPosition="right" />
I want to send the updated props to a child component, If it is possible without copying or cloning to a new object, Please help me how can I achieve this.
Solution is as simple as:
<ChildComponent {...this.props} legendPosition="right" />
Of course legendPosition will be available in ChildComponent by this.props.legendPosition.
Of course earlier this.props can contain already legendPosition property/value which will be overwritten by defined later - order matters.
Of course there can be many spread operators - for multiple properties, logic blocks ... whatever:
const additonalProps = {
legendPosition: 'right',
sthElse: true
}
return (
<ChildComponent {...this.props} {...additonalProps} />
)
below in tempProps object spread operator copy your this.props object and after spread operator we can add new object property or we can update existing object property.
var tempProps = {
...this.props,
tempProps.legendPosition = 'right' //property you want to add in props object
};
Your answer is in this line.
var tempProps = this.props;
this.props is immutable that means you can not change the property value in function.
you can use a this.state so you can modify it in your function
props --- you can not change its value.
states --- you can change its value in your code, but it would be active when a render
happens.
For anyone getting this error with jest, make sure to mock your component this way:
jest.mock('component/lib', () => ({
YourComponent: jest.fn()
}))
Then in your test you can mock the implementation:
(YourComponent as jest.Mock).mockImplementation(() => <div>test</div>);
Hope this works
You can define default values for your props properly by assigning to the special defaultProps property:
https://reactjs.org/docs/typechecking-with-proptypes.html
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
// Specifies the default values for props:
Greeting.defaultProps = {
name: 'Stranger',
};
I'm learning React. It seems to me that HOC like the following example from React's official docs:
function withSubscription(WrappedComponent, selectData) {
// ...and returns another component...
return class extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
data: selectData(DataSource, props)
};
}
componentDidMount() {
// ... that takes care of the subscription...
DataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange);
}
handleChange() {
this.setState({
data: selectData(DataSource, this.props)
});
}
render() {
// ... and renders the wrapped component with the fresh data!
// Notice that we pass through any additional props
return <WrappedComponent data={this.state.data} {...this.props} />;
}
};
}
can be rewritten in this way:
class WithSubscription extends React.Component {
constructor({ component, selectData, ...props }) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
data: selectData(DataSource, props)
};
}
componentDidMount() {
DataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange);
}
handleChange() {
this.setState({
data: selectData(DataSource, this.props)
});
}
render() {
return <component data={this.state.data} {...this.props} />;
}
}
Then use it like this:
<WithSubscription component={BlogPost} selectData={(DataSource) => DataSource.getComments()} />
Are they both HOC? When is one style preferred than the other?
I was struggling with HOC too at first. Another way of looking at this is at wrappers of components that you could use to isolate the functionality from one component.
For example, I have multiple HOC. I have many components that are only defined by props, and they are immutable once they are created.
Then I have a Loader HOC Component, which handles all the network connectivity and then just passes the props to whatever component is wrapping (This would be the component you pass to the HOC).
The loader does not really care which component it is rendering, it only needs to fetch data, and pass it to the wrapped component.
In your example, you can actually accomplish the same, however it will become much more complex once you need to chain multiple HOC.
For example I have this chain of HOCs:
PermissionsHOC -> LoaderHOC -> BorderLayoutHOC -> Component
First one can check your permissions, second one is loading the data, third one is giving a generic layout and the forth one is the actual component.
It is much easier to detect HOCs if you realize that some components would benefit from having a generic logic on the parent. You could do the same in your example, however you would need to modify the HOC every time you add a child component, to add the logic for that one. Not very effective. This way, you can add new components easily. I do have a Base component which every component extends, but I use it to handle the helper functions like analytics, logger, handling errors, etc.
What they call an "HOC" is basically a function (just a regular function, not React specific) that behaves like component factory. Meaning it outputs wrapped components that are the result of wrapping any inside-component of your choice. And your choice is specified with the "WrappedComponent" parameter. (Notice how their so-called "HOC" actually returns a class).
So I don't know why they called it an "HOC" tbh. It's just a function that spits out components. If anyone knows why I'd be interested in hearing the reason.
In essence their example is doing exactly what you're doing, but it's more flexible because WrappedComponent is being taken in as a parameter. So you can specify whatever you want. Your code, on the other hand, has your inside component hard coded into it.
To see the power of their example, let's say you have a file called insideComp.js containing:
import withSubscription from './withSubscription';
class InsideComp extends React.Component{
// define it
}
export default withSubscription(InsideComp);
And when you use insideComp in another file:
import myComp from './insideComp.js';
You're not actually importing insideComp, but rather the wrapped version that "withSubscription" had already spit out. Because remember your last line of insideComp.js is
export default withSubscription(InsideComp);
So your InsideComp was modified before it was exported
The second one is not a HOC.
They coin the word HOC from higher order functions. One example of a higher order function is a function that takes a function as an argument and returns another function.
Similarly, a HOC is a function that takes an component as argument and returns another component.
This does sound weird to me because a higher order component is not a react component; it is a function instead. I guess the reason they call it HOC is because:
A react component is a class, which is indeed a constructor function in JavaScript (except that functional components are simply functions). A HOC actually takes a function (a constructor function) and returns another function (another constructor function), so it is actually a higher order function if you think about it. Probably because it is in the react context and this is a pattern to transform components, they call it HOC.
As to the difference between the two styles you mentioned:
First one: you would use the first one to generate a class like MyComponnet = withSubscription(AnotherComponent, ...), and whenever you need it in a render call just write <MyComponent><MyComponent>
Second one: this is less common. Every time you need it in a render call, you would need to include the WithSubscription component as you mentioned in the description <WithSubscription component={BlogPost} selectData={(DataSource) => DataSource.getComments()} />
I'm wondering what the best practices are for defining propTypes on a component that will be wrapped with a 3rd-party HOC, in this case, withRouter() from React-Router.
It is my understanding that the point of propTypes is so you (and other developers) know what props a component should expect, and React will give warnings if this is violated.
Therefore, since the props about location are already passed by withRouter() with no human intervention, is it necessary to worry about them here?
Here is the component I'm working with:
const Menu = ({ userId, ...routerProps}) => {
const { pathname } = routerProps.location
return (
// Something using userID
// Something using pathname
)
}
Menu.propTypes = {
userId: PropTypes.number.isRequired,
// routerProps: PropTypes.object.isRequired,
// ^ this is undefined, bc withRouter passes it in later?
}
export default withRouter(Menu)
//.... in parent:
<Menu userId={id} />
What would be the convention in this case?
It is my understanding that the point of propTypes is so you (and other developers) know what props a component should expect, and React will give warnings if this is violated.
This is correct.
What would be the convention in this case?
I don't think you will find a definitive answer to this. Some will argue that if you define one propType you should define all expected prop types. Others will say, as you did, that it wont be provided by the parent component (excluding the HOC) so why bother. There's another category of people that will tell you not to worry with propTypes at all...
Personally, I fall into either the first or last category:
If the component is for consumption by others, such as a common ui component (e.g. TextField, Button, etc.) or the interface for a library, then propTypes are a helpful, and you should define them all.
If the component is only used for a specific purpose, in a single app, then it's usually fine to not worry about them at all as you'll spend more time maintaining them than debugging when the wrong props are passed (especially if you're writing small, easy to consume functional components).
The argument for including the routerProps would be to protect you against changes to the props provided by withRouter should they ever change in the future.
So assuming you want to include the propTypes for withRouter then we need to breakdown what they should actually be:
const Menu = ({ userId, ...routerProps}) => {
const { pathname } = routerProps.location
return (
// Something using userID
// Something using pathname
)
}
Looking at the above snippet, you may think the propTypes should be
Menu.propTypes = {
userId: PropTypes.number.isRequired,
routerProps: PropTypes.object.isRequired
}
But you'd be mistaken... Those first 2 lines pack in a lot of props transformation. In fact, it should be
Menu.propTypes = {
userId: PropTypes.number.isRequired,
location: PropTypes.shape({
pathname: PropTypes.string.isRequired
}).isRequired
}
Why? The snippet is equivalent to:
const Menu = (props) => {
const userId = props.userId
const routerProps = Object.assign({}, props, { userId: undefined }
const pathname = routerProps.location.pathname
return (
// Something using userID
// Something using pathname
)
}
As you can see, routerProps doesn't actually exist in the props at all.
...routerProps is a rest parameter so it gets all the other values of the props, in this case, location (and maybe other things you don't care about).
Hope that helps.
I can't seem to grasp the understanding of why higher order components are highly valued over the regular components? I read a tutorial on them and that higher order components are good because they: 1) Allow code re-use, logic and bootstrap abstraction. 2) Able to do render highjacking. 3) Able to abstract state and manipulate them. 4) Able to manipulate props. Source: link
An example of a higher order component in code was shown there as:
function refsHOC(WrappedComponent) {
return class RefsHOC extends React.Component {
proc(wrappedComponentInstance) {
wrappedComponentInstance.method()
}
render() {
const props = Object.assign({}, this.props, {ref: this.proc.bind(this)})
return <WrappedComponent {...props}/>
}
}
}
These look almost the same exact code as a regular class definition that receives props and you are still able to "manipulate props" and "manipulate state" inside that class
class Something extends React.Component {
constructor(props) {
super(props);
this.state = { food: 'no_food_received_yet' }
}
componentDidMount() {
this.setState({ food: 'apple' });
}
render() {
return (
<div>
<p>{ this.state.food }</p>
<h2>{ this.props.food }</h2>
</div>
);
}
}
Actually I didn't get to manipulate or mutate the props but I can just receive them, apply them to state and output that state.
This is not to bash on higher order components---this is actually the complete opposite. I need to understand where I am wrong and why I should integrate higher order components into my react app.
HOCs are absolutely useful, but they're useful in the same way any "higher order" function is.
Consider the following component:
let Button = props => <button style={{ color: props.color }} />
You could make another component called BlueButton:
let BlueButton = props => <Button color="blue" />
There's nothing wrong with that, but maybe you want any component to be able to be blue, not just a button. Instead we can make a generic HOC that "blueifies" the passed component:
let blueify = Component => props => <Component {...props} style={{ color: 'blue' }} />
Then you can make blue buttons, blue divs, blue anything!
let BlueButton = blueify(Button)
let BlueDiv = blueify(props => <div {...props} />)
Imagine you had an app where certain screens were private and only available to authenticated users. Imagine you had 3 such screens. Now on each screen's container component you can have the logic to check if the user is authenticated and let them through if they are, or send them back to login when they are not. This means having the exact same logic happen 3 times. With a HOC you can code that logic just once and then wrap each private screen in with the HOC thus giving you the same logic over and over, but the code only needs to exist in one place. This is an example of great code reuse that HOCs offer.
Higher order components are more generalized, and so in theory can be applied to a broader number of cases. In the more general sense, higher-order components (and higher-level languages) tend to be more expressive.
In your case, the difference is readily apparent. The non-generalized (lower-order) component has hard-coded HTML in it. This is programming 101; constant declarations like PI are preferred over hard-coded declarations like 3.14159 because they give meaning to magic numbers and allow one point of modification.
A simple example of a higher order "component" (in this case a higher order function) is a sort function that takes as one of its arguments an ordering function. By allowing the ordering to be controlled by an outboard function, you can modify the behavior of the sort without modifying the sort function itself.