How to change props name in React components? - reactjs

Let's say I want the consumer of my component to give me this props:
<MyComponent
firstProp='first value'
secondProp='second value'
/>
And I have an internal state inside my component, called firstProp.
I know I can either change the name of the internal state, or change the prop name.
But this is a simple example. In reality in our codebase we have a huge dependency and hierarchy of components and it's not easy for us to change names.
I wonder if it's possible that I change the name of firstProp I recieve in my component to something else?

in your consumer component :
const {firstProp:yourPrefferedName} = props

Related

Why do we need a `props` parameter in React?

I still don't get why we need a prop(s) in react, seriously. Why can't we just declare everything we need as an argument or parameter in the child component, then declare it, why do we have to declare it in a parent element then pass the props to the child component then catch it. I don't understand why. It seems a bit confusing, I'm yet to see the why in it
Props are useful in the case that you have a controller in the parent component and you want to pass the value of that controller to the child to make a certain action. The replacement for props would be to store everything globally in redux or mobx, but that needs much work. for example
const ParentComponent = () =>{
const [flag, setFlag] = useState(false)
return(
<div>
<button onClick={()=>setFlag(!flag)}>click me!</button>
<ChildComponent flagValue={flag}/>
</div>
)
}
as in the example for some reason the button that changes the flag is in the parent and you need to use that value in the ChildComponent. So here you benefit a lot from using props.
Also in writing a cleaner code and drier one so as not to repeat the same values in different react components
You might not be familiar with React if you ask such questions (no anger at all). It's one of the main concepts of the React library.
You can easily split a huge component into smaller pieces. But then, you need to provide the same data here and there. To prevent repeating yourself (DRY - don't repeat yourself), you can share the prop with many child components.
If you are interested in React - check the documentation.
It's one of the prettiest documentation I've ever read.
prop changes trigger UI re-render for the child component.
That's one of the props of using props.

Should a React component prop be required when the data is fetched from the backend API?

Like any other app, for rendering a specific section of my React app, I'm expecting to receive a list of items from my backend API. I've created a typical Card component to display the data of each item. This Card component has a parent component which is common for all of the items. It would be something like this:
<ParentComponent>
<CardItem headline image/>
</ParentComponent>
The props headlineand image are required, so in theory, I should always receive them from my API. Therefore, I've set these props as required in my component:
CardItem.propTypes = {
headline: PropTypes.string.isRequired,
image: PropTypes.string.isRequired,
}
As we all know, as our app grows, it can always happen that for some specific reason, even though these props are required, I could receive an undefined value. For this reason, I like doing my components bulletproof and, even though those props are required, I always do a conditional rendering for avoiding the app to break:
{headline && (
<Component/>
)}
For other components I just check at the very top if the prop exists, otherwise, I return null:
if (!itemId) return null
While unit testing my components, I make sure this behavior is tested so that if I receive any undefined vale from my API, the app doesn't break. I've realized that Jest keeps warning me because of this:
Warning: Failed prop type: The prop headline is marked as
required in CardItem, but its value is undefined.
It makes me wonder if my approach is not the right one so here my doubts:
Is my approach correct and there is a way to avoid these warnings on Jest?
Should the props of a component never be required when the data is received from an API?
Instead of checking in the component children, the parent component should not render the children if the props don't exist? - This one feels like it is not the correct one at all but I'm adding it just in case it is a valid approach.
Please don't let your response be influenced by the fact that I'm checking props like headline or image, I know for something like this I can always render conditionally. Think more of the case of an itemId or similar which are props 100% required for the correct rendering/behavior.
In the components, there is an option of defaultProps.
In the case, that you don't receive the props from the API. You can provide your own defaultProps to the component.
if you are using the functional component, It would be something like this outside the component
CardItem.defaultProps = {
headline: "YOUR_DEFAULT_VALUE",
image: "YOUR_DEFAULT_VALUE",
}
and if you are using a class component, it would be something like this inside the class
static defaultProps = {
headline: "YOUR_DEFAULT_VALUE",
image: "YOUR_DEFAULT_VALUE",
}
and by doing this, you don't need to validate the props
See there can be multiple scenarios,
1. Children totally depends on parent for data. In this case parent should not render child if props are undefined/null. i.e rendering of children should be bulletproof.
2. If children is independent in sense that it makes sense if parent somehow doesn't provide props to it and still it can work with some default values then you can render the children. But here comes the approach you wanna take, as mentioned in above answer there's defaultProps. but if you don't wanna go with it, then you can try something like this,
interface ComponentProps {
prop1?: string;
prop2?: number;
}
export const Component:React.FC<ComponentProps>=({prop1='',prop2=0})=>{
return(
// logic goes here
)};
Now when you test this component Jest will not complain and you can test the values easily.

Change of state in another component

How to solve the problem attached in the drawing?
I am talking about the best possible way of getting used without using redux.
When a button is pressed in a nested component, something has to change in another (it does not inherit from itself)
For example, in one component I choose the element and in the other I want to display details.
You can have a shared parent hold the state you want to change and pass to the first component while sending the onClick function to the other. Then, when one component changes the state through the onClick function, the changed prop will be passed on to the second component.
You should not change the state from one component via another component:
https://reactjs.org/docs/faq-state.html
props get passed to the component (similar to function parameters)
whereas state is managed within the component (similar to variables
declared within a function).
For "States" between components, you should use props from the store, via react-redux
First of all, I will suggest you to look into lift state up in react.
Now, how you'll do it: (just a pseudo example)
ParentComponent
onClick={this.onClick} stateProps={this.state.stateProps}
onClick() {
this.setState()
}
ComponentA
onClick={props.onClick}
ComponentB
console.log(props.stateProps)
The component will be used like: (again just a pseudo example)
<ParentComponent onClick={this.onClick} stateProps={this.state.stateProps}>
<ComponentA onClick={props.onClick} />
<ComponentB stateProps={props.stateProps} />
</ParentComponent>

Why are React props immutable?

I've been reading React's Quick Start documentation;
Whether you declare a component as a function or a class, it must never modify its own props
This is a "pure" function, because it doesn't attempt to change its inputs, and always returns the same result for the same inputs:
function sum(a, b) {
return a + b;
}
This in an "impure" function, because it changes its own input:
https://codesandbox.io/s/9z38xv4x7r
function SayHi(props) {
props.name = "Jim"; // TypeError Cannot assign to read only property 'name' of object '#<Object>'
return <h1>Hi {props.name}!</h1>;
}
Why are React props read-only?
A component should manage its own state, but it should not manage its own props. props is essentially "state that is managed by the component owner." That's why props are immutable.
React docs also recommends to treat state as if it's immutable.
That is because by manipulating this.state directly you are circumventing React’s state management, which can be potentially dangerous as calling setState() afterwards may replace the mutation you made.
You may think of React component as a function of its props and state. As you advance through the docs, you'll find that this is the case, as most functions in the React component life cycle have signatures of the form (prop, state) => { //code }.
React docs define props as any arbitrary input given to a component, and the component will render something based on the props ( and sometimes based on state too, if it is a stateful component ). So props is like something that is given to the component for say, reference. Imagine it this way: you are a component, and your parent component gives you a reference book, containing some rules on how you must behave ( a.k.a. render ). Two cases may arise:
You are dumb (stateless): You just read the book, and behave so.
You are smart (stateful): You read the book, and then note some things in your notepad, that you may view, update or delete. You may even take copy down content from the book to your notepad, and then edit the notepad.
Either way, you may not update the reference book given to you. Only the parent component can update it ( example, give you another book, or change its content ).
I don't know if this is a correct representation, but React components work in a similar way. You'll get the hang of it soon. Make sure you read Thinking in React too. Happy coding!
The props of a react component is aimed to store values and functions from its parent component. It's just the pattern, props are immutable. If you want to have a variable that would be mutable, then store it in the state of the component. States are mutable.

React props states and Redux

What is the different between states and props?
How can you pass a value of let's say CompomentA to ComponentB if we have have for example ComponentA which takes an input then ComponentB is suppose to output(to print it on the screen) that same value if we have a third component called CompomentContainer which is a container of both A and B?
What is Redux? the definition of redux on the main website does not make sense to me. How does it work exactly? How is it useful to react?
Please bear with me, I hope my questions make sense. Thank you.
Those are very valid questions. I've been there and I know how frustrating it is to read about redux and not understanding anything. For some reason people like to use fancy words, which sounds complicated but in reality things are very simple and easy.
What is Redux?
Redux is a Flux architecture. In simple words it will help you to manage the global state of your app.
How does it work exactly?
Redux will create a single "store", this store will have all the data that you need to render in your components, you can update the data using "actions", you will call the actions from your components, these actions will transfer the new data to the "reducers", inside of a reducer you will basically copy the data from the components to the global state (reducers should be pure functions).
How is it useful to react?
It's very useful! Mainly because you will be able to share data across components. Also by having a global state you could save it to the local storage (or a database) to add offline support.
What is the different between states and props?
You can define props to describe the properties that the component will receive when creating instances, you can think of props like parameters, for example:
<MyComponent name="Crysfel" lastname="Villa" />
The previous component is receiving two props, name and lastname. Props will allow you to send data from ComponentA to ComponentB, assuming ComponentB is a child of ComponentA. Props will also help you to receive data from redux. As a rule of thumb, you should never modify the value of the props, these values are just to receive data.
State on the other hand is an object that might contain configurations for your component, the idea is to handle the state of the component, for example a collapsible container, you could have a toggle property in the component's state and toggle the value when user clicks a button. However when using redux you will rarely use the component's state, because Redux is managing the state of your app.
For your second question about sending data between component, you would use redux for that, ComponentA should call an action and send the new data to the global state, then redux will update your component with the new data and then you can render the new data into ComponentB (using props).
What is the different between states and props?
State is data that is tied directly to the React component in which it is set. Props is data that is passed into a child component from the parent component. Unlike state, props are immutable and never "set" directly.
How can you pass a value of let's say CompomentA to ComponentB if we have have for example ComponentA which takes an input then ComponentB is suppose to output(to print it on the screen) that same value if we have a third component called CompomentContainer which is a container of both A and B?
To pass value from Component A to ComponentB you would provide the value as props, passed in via the ComponentA render function. Something like this:
class ComponentA extends React.component {
render() {
return <ComponentB myvalue={value} />
}
}
In ComponentB the value can be accessed: this.props.myvalue
What is Redux? the definition of redux on the main website does not make sense to me. How does it work exactly? How is it useful to react?
Redux is an implementation of the ideas of Flux with a few architectural differences. You can think of it as a library that helps you create a central data store that passes data one-way into React components. It allows you to maintain global state outside of the components themselves.
A top-level container component typically listens to the store and re-renders whenever the store data changes (see the connect function). The data is then passed from the container component into the children components that need that data so they can render properly.

Resources