NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

reactbase-for- parrent-and-child-call
==================================
// https://jsfiddle.net/Saravanan_Rajaraman/q1w5qk9r/1/

class Hello extends React.Component { //parent calss

onChangeInHello = (e) =>{
console.log("onChangeInHello", e);
}

onBlurInHello = (e) => {
console.log("onBlurInHello", e);
}

onFoucsInHello = (e) => {
console.log("onFoucsInHello", e);
}

render() {
return (
<div>
<Label name="Enter your name : " ></Label>
<Text onChange={this.onChangeInHello} onFoucs={this.onFoucsInHello} onBlur={this.onBlurInHello}/>
</div>
)
}
}

class Label extends React.Component { //child class 1
render() {
return (
<label>
{this.props.name}
</label>
)
}
}

class Text extends React.Component { child class 2

constructor(props){
super(props);
this.state = {
isFocus : false
}
}

onFoucs = (e) =>{
console.log(e);
this.setState({isFocus: true});
this.dispatchOnFocus('onFoucs',e);
}

onChange = (e) =>{
console.log(e);
this.dispatchOnFocus('onChange',e);
}

onBlur = (e) =>{
console.log(e);
this.setState({isFocus: false});
this.dispatchOnFocus('onBlur',e);
}

dispatchOnFocus = (type,context) => {
if (this.props[type]) { //==> this.props.type
this.props[type](context);//==> this.props.type(context)
}
}

render() {
return (
<input type="text" onFocus={this.onFoucs} onChange={this.onChange} onBlur={this.onBlur}/>
)
}
};







ReactDOM.render(
<Hello />,
document.getElementById('root')
);
====================**************===============
Best practices for writing a react component
REACT Component Overview:-
React Elements:-Elements are the smallest building blocks of React apps. React elements are immutable. If it is required to change the UI of the page, we need to put the elements in the ReactDOM.render ()
Example:
We have an element displaying time.
<div>
<h1>Hello, world!</h1>
<h2>It is {newDate().toLocaleTimeString()}.</h2>
</div>
Being immutable, this div will display time when it is created and that time will not change.
If we want the time to change we will put the same element under ReactDOM.render(). And call the render function to get the updated time displayed

function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(
element,
document.getElementById('root')
);
}
setInterval(tick, 1000);

here setnterval is calling tick() which is further calling the render function to display the updated time.
Components:-Components are like javascript functions, which will take the inputs and return React elements, describing what to be displayed on the screen.
Guidelines for making COMPONENT:-
1. Component should be written as a pure function (react prefer/stateless function): do not attempt to change their inputs, and always return the same result for the same inputs
2. The input values of component are called its properties or props. These props can be simple values or functions. One can never change the values of props.(as stated in point 1)
3. If no state/lifecycle involved then better to have create component using function(called stateless component). Make such function as arrow functions.
Example:
Const Welcome(props)=>{
return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
element,
document.getElementById('root')
);

4. The class component will have a render () which will be called every time the state is changed re-render the react elements getting displayed for the respective component.
Example:-
class Tick extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}

render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
5. Return should always return one element
return(<div>inside one parent you can have other elements</div>)
6. Name component with first letter capital, otherwise react compiler will mistake react component as HTML element, and will not give desired output.
7. Never make unnecessary state. Make state only when the change in the value of respective property (which we consider as state) will control the rendering of the page or component.
8. There should not be any inline function.
Example:
<Tick onChange= {()=> {}}/> --> wrong

handleClick= ()=>{}
<Tick onChange={ handleClick } -->correct
9. Use setState({state:newstate}) to set state.
10. While setting state, the value of state should change. Data types which are called by reference like arrays, objects etc always make new object or array using spread operator, filter etc which give new array or object. If not done this way, the state change would not be reflected as it is by reference.
11. Don’t modify state directly. Modify the state in constructor or in class property (to set initial state) or any function call which leads to state change
12. React merges the object you provide into the current state. Your state may contain several independent variables. you can update them independently with separate setState() calls
Example:
constructor(props) {
super(props);
this.state = {
posts: [],
comments: []
};
}
Can set state separately:
fetchComments().then(response => {
this.setState({
comments: response.comments
});
});
fetchPosts().then(response => {
this.setState({
posts: response.posts
});
});

13. state is often called local or encapsulated. It is not accessible to any component other than the one that owns and sets it. A component may choose to pass its state down as props to its child components
example : <FormattedDate date={this.state.date} />



14. Use map function to render array list items. Add a key attribute to the element inside array, it improves our rendering
Example:
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
15. Destructuring the props to respective constants will make the code more readable
16. Always use default props for non-required props field. It makes sure your component is doing what you expect it to do and eliminates certain type checks and informs other developers about their usage. PropTypes let developer know what props are being used for current component.
17. Try to split the components into smaller components to make it more readable
18. The constructor for a React component is called before it is mounted. Avoid introducing any side-effects or subscriptions in the constructor. Use mainly for initializing state or values.
19. componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering. If any service call response required to render in component can be invoked in componentWillMount lifecycle method
20. componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, cancelling network requests, or cleaning up any subscriptions that were created in componentDidMount().
CSS/Style:-
21. All the css properties should be done using styled component
22. No css file to include inside components
23. Style Component name should be in camel case and started with a capital letter
24. Font name and size should come from a shared file
25. Colours shouldn’t be hardcoded, that should come from a shared file where all colour codes defined
26. If the component file is longer then all styled component definitions should be moved to a different js file and then it can be imported in component file
27. You can make conditions in styled component using props
28. Responsive layout should be taken care in styled component by importing the styles/media.js and apply the screen size conditions accordingly
29. Define the style components at end of the file(if it is included in the same component js file)
30. For more detail in styled component check the link https://www.styled-components.com/
Naming Convention:-
31. Component Class/Function name should be in camel case and started with a capital letter.
// Bad
class myComponent extends React.Component {

// Good
class MyComponent extends React.Component {

32. File name also in same format and followed by the extension
//Bad
my-component.js
//Good
MyComponent.js

33. Method names should be camel case and the name should be more descriptive
34. Type name should be started with capital letter



Test case (using JEST):-


35. Create test case of the component. under component folder create a new folder called '__test__'
36. Create a test file as per the format - [component_name].test.js
37. Write the test cases as per the requirement
38. Test case should render the component by using enzyme
39. Use contains instead of find.
40. If any service call is happening in componentwilmount(). On mounting that particular component, assign a mock function to the componentwillmount() and then mount the component.
Example:
const willMount = jest.fn(),
compoenetName.prototype.componentWillMount() = willmount
const wrapper= mount(componentName)


Storybook:-

41. Write a story for this component in storybook environment
42. Create different levels(menu) if the component has more features to explain


Steps For Making a Component:-
1. Define proper folder structure:-
i. Create a folder for the component under shared/components. Name will be camel case with first letter as capital
ii.
Feature component:-
i. Create a test folder, having the test case for respective component.
ii. Create index.js under this new created folder, which will hold the routing.
iii. Create page.js which will have the component need to be displayed when the index.js of the respective folder is called.
iv. Whenever the respective component is called, the index.js file of its folder is called, which define the route for component and route calling the respective page.js.
v. The url showing in the browser should be same as the folder structure following.
Core-> pages->login->index.js
Page.js
For calling the login folder page.js, url should be /core/login
Shared Component:-
i. This folder will have one folder for test case and index.js
ii. Here the index.js have the component definition which needs to be displayed.
iii. Whenever a shared component is called, the index.js of its respective folder is called.
2. Write Flow Section:
i. the first line of any component should be // @flow.
ii. All component const, variables, objects should have flow type compatible.
iii. After end of the development need to run the below command to see if there is any flow error to fix:
npm run flow

iv. Shouldn’t use generic types for example Function, Object or any to fix the flow error. It should have a proper type.
v. Check the shared flow types available and if it is going to use in different places then better to define it under flow/types.js and use
vi. For more detail in flow type syntax check the link https://flow.org/en/docs/types/
3. Write Import Section:-
i. Include the in-build react libraries as per the requirements.
ii. Import the other dependencies like components, constants, types, styles etc.
iii. While importing a class based component, make sure using the same name as component.
4. Write types and variable declaring section:-
i. Always define type for props, even if the component does not have any props.
ii. Name the type for props as Props.
iii. Name the type for state as State, if needed.
iv. Define variable only as const in this section.(to maintain component as a pure function)
v. First letter should be capital for a const.
vi. We can export the declared const and type also.
5. Write the component:-
i. Follow the guidelines in section Guidelines for making COMPONENT
ii. Can be class based or function.
iii. If there is any state involved then need to make stateful component. It will be developed with class based components.
iv. First initialize State:-
Two ways to do initialization:-
In constructor():initializing:-
class Tick extends React.Component<props,state> {
constructor(props) {
super(props);
this.state({comment: 'Hello'});
}
In Class: initializing:-
class Tick extends React.Component <props,state>{
state= {comment: 'Hello'}

}

v. After initializing, write lifecycle methods if required.
vi. Define functions which are used within the component.
vii. Now define render ()(in case using class based component)
6. Write the styled component section - Refer section for guidelines.


     
 
what is notes.io
 

Notes.io is a web-based application for taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000 notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 12 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.