← Toggle hide and show in Reactjs | display form on button click - part 14
Are you seeing red text or underlining in your text editor, terminal, or browser screen? If so, there may be a flaw in your code. Red is always a symbol for mistakes, whether it be on a student's notepad or a developer's code editor. Perhaps, as a result, border 1px red became a CSS debugging method. I'm unromantic please excuse me!
When using React, we frequently make mistakes or leave bugs that cause errors and prevent the application from rendering. I'll describe how to fix these issues in this post
Avoid These Common Mistakes
When we work with react applications, we make a lot of mistakes, especially in the beginning, because we are not used to it, and as a result, we waste a lot of time, hour after hour, day after day.
Here is a list of the topics I will discuss in this article.
- Leave off the capital letter when naming components
- Return a component with multiple parent elements
- Understanding error messages
- forget to add a unique "key" prop to each child in a list
- A number is passed to the component as a string
- calling state immediately inside the component function
- Set the input value without using onchange
- Modify the state manually
It will not only inform you of the common mistakes you are likely to make, but I also want you to review what you have already learned.
Leave off the capital letter when naming components
We frequently forget to use capital letters at the start of component names since we are used to naming files and functions in small characters.
function hello = () => {
return <div>Hello World!</div>
}
function App = () => {
return <hello />
}
This will result in a blank page with nothing displayed, and inside the developer tools, we'll encounter the error "unrecognized."
This occurred as a result of React treating it as an HTML tag and converting it to a string. Rename the function 'hello' to 'Hello' to fix this.
function Hello = () => {
return <div>Hello World!</div>
}
function App = () => {
return <Hello />
}
Return a component with multiple parent elements
When you first start creating React Apps, this is most likely to happen, we confuse JSX with HTML because they are similar in some ways.
Examine the code below, which contains two parent elements.
const Error = () => {
return (
<h1>Why can't we have</h1>
<p>Multiple parent elements</p>
)
}
You will receive an error about an enclosing tag.
React runs in the background and JSX is converted into javascript functions, which is why when we return multiple elements in one component, it returns two values side by side and it is invalid. one function cant' return two statements.
return React.createElement("h1", null, "Why can't we have")
React.createElement("", null, "Multiple parent elements")
To solve this issue, wrap them in a single div element, then utilize as many nested elements inside of it as you like.
return (
<div>
<h1>Why can't we have</h1>
<p>Multiple parent elements</p>
</div>
)
As an alternative, you can put the elements in an empty tag known as a fragment that only returns one value.
return (
<>
<h1>Why can't we have</h1>
<p>Multiple parent elements</p>
</>
)
Understanding error messages
You may encounter several errors while developing a React application. I'll list a few typical error messages and what you might be doing incorrectly. I'll explain why it happened so you can address the problem without searching online, which is a better approach to becoming React ninja.
- Error: Module not found
This error informs you that your relative path is incorrect and that you forgot to add "./", which tells you the file is in the same folder.
React will treat your file as being outside of the "src" folder if you import it with just the "/Home" line.
import Home from './Home
- Error: Can't resolve
If you get this error, it means you have a problem with the module location.
If the file is nesting inside another folder, you must supply every parent folder and also check for typos. You must first understand the distinction between "./" and "../".
Locations that begin with "./" denote that a file is in a similar folder; for example, "./Home" indicates that a file is in the src folder, and "./component/Header" indicates that a file is inside the component folder.
Locations that begin with '../' indicate that the file is located outside of the current directory, so ../card/button means that the button file is located outside of the component folder but within the card folder.
What I'm describing is the folder structure shown below.
📁src/
Home.js
📁component/
Header.js
📁card/
Button.js
Make certain there are no typos and double-check the location of your file.
- Error: module has no exports
You make components usable by splitting them into small files, but as you nest more components, you may forget to export them as default export.
Always export the file before importing it into any component, and remember not to use curly braces around it if you are using default export; curly braces can be used if you are using named export.
export default function User() {
const name = 'elpeeda'
return (
<h1>{name}</h1>
);
}
export function Message() {
return (
<p>If you have any query, please comment below!</p>
);
}
import User from './User'
import {Message} from './Message'
- Error: 'X' is not defined
This error clearly indicates that React was unable to locate the specified pointer function, object, or argument in that file.
You should examine that file, search for the line name error it suggests, and analyze what you did incorrectly because, often, you made a typo in which a letter should have been capitalized instead of small or vice versa.
Other scenarios include utilizing a component without first importing it, using an object that doesn't exist, forgetting to specify a function, or neglecting to assign an argument.
Look up in the code what I'm doing wrong here.
function handleDoubleClick = () => {}
<button onClick={handledoubleClick}>Double Click</button>
Check all the given points above and I'm sure you'll get better as you debug your code.
Forget to add unique "key" prop to each child in a list
If your application contains a list of data that needs to be transformed using a map, there's a good possibility you haven't specified a unique key and are therefore receiving the following warning: Each child in a list should have a unique "key" prop.
const blogLists = ['elpeeda', 'CSS-tricks', 'freeCodeCamp', 'GeeksforGeek']
function App() {
const [lists, setLists] = useState(blogLists)
return (
<div classname="App">
{lists.map(list => {
return <p>{list}</p>
})}
</div>
);
}
In the beginning, we tend to forget to add key props when we render the list of items or components on the screen. You must provide a "key" attribute that must be distinct for React to detect each child element. React makes it easier to tell which element has been modified and which has been removed.
const blogLists = ['elpeeda', 'CSS-tricks', 'freeCodeCamp', 'GeeksforGeek']
function App() {
const [lists, setLists] = useState(blogLists)
return (
<div className="App">
{lists.map(list => {
return <p key={list.toString()}>{list}</p>
})}
</div>
)
}
In the real world, we obtain the unique ID from a database, however, in some cases, we have a different option.
- You can supply a unique id inside the array and pass the key prop.
- You can use a random function with string to generate unique keys/ids and use that.
- We can utilize the javascript date object and prefix item, for example- username, when iterating through a list of items.
- Index as Key - This is okay to use an index if the elements are not deleted or added to them, but if they are, you may experience strange side effects because React will associate the keys with incorrect components.
const blogLists = ['elpeeda', 'CSS-tricks', 'freeCodeCamp', 'GeeksforGeek']
function App() {
const [lists, setLists] = useState(blogLists)
return (
<div className="App">
{lists.map((list, index) => {
return <p key={(index)}>{list}</p>
})}
</div>
);
}
A number is passed to the component as a string
React takes every props as string type if it's quoted and not wrapped in curly braces, It will be parsed as string. Curly braces should be used around any numbers or expressions you plan to send as arguments to a component.
const App = () => {
return (
)
}
const User = ({age}) => {
return (
Lily is {age}
)
}
Calling state immediately inside the component function
Managing state is difficult, especially for beginners. When you call the set function directly within the component, the component will re-render infinitely with the same props, causing React to keep setting the state and re-rendering, leaving the screen blank.
Here is an example of putting a setter right into an onClick event handler, which will immediately invoke the event handler.
const App = () => {
const [bgColor, setBgColor] = useState('pink')
return (
<button onClick={setBgColor('blue')} style={{backgroundColor: bgColor}} type='button'>Button</button>
)
}
To solve the infinite re-rendering problem in React, call the setBgColor method inside the arrow function and then trigger it with an event.
const App = () => {
const [bgColor, setBgColor] = useState('pink')
return (
<button onClick={() => setBgColor('blue')} style={{backgroundColor: bgColor}} type='button'>Button</button>
)
}
Set the input value without using onchange
If you're dealing with a form and trying to input a value to store it in the state and update it if the value changes, you're probably having trouble.
const User = () => {
const [name, setName] = useState('')
return (
<form>
<label>{name}</label>
<input value={name} type='text'/>
</form>
)
}
To access the value typed in the input field, we connect the input element with state in React, which is referred to as a controlled component. in order to address the problem we must use the onChange event on the input to alter the state as the input value changes.
const User = () => {
const [name, setName] = useState('')
return (
<form>
<label>{name}</label>
<input value={name} type='text' onChange={(e) => setName(e.target.value)}/>
</form>
)
}
Every time we entered a value into the input field, the onChange event was triggered.
Not Using the state setter function
Don't only rely on the variable value to update the new value if you have an array that stores values and you wish to update that list; you can have odd behavior.
For example, if you have a list of blogs and want to add a new blog to that list, you can do so with setLists(['elpeeda',...lists]), but if for some reason you ran the set method twice, the value will not be rendered twice.
const blogLists = ['CSS-tricks', 'freeCodeCamp', 'GeeksforGeek']
function App() {
const [lists, setLists] = useState(blogLists)
const addBlog = (newVal) => {
setLists(['elpeeda', ...lists])
setLists(['elpeeda', ...lists])
}
return (
<div className="App">
{lists.map(list => {
return <p key={list.toString()}>{list}</p>
})}
<button onClick={addBlog} type='button'>Button</button>
</div>
);
}
React acts in this way because when a component is re-rendered, a variable is not updated right away and has no chance to update its previous value.
When updating a value depending on past values, using a setter function is recommended. It will first get the old value before updating the new one using the old state.
const blogLists = ['CSS-tricks', 'freeCodeCamp', 'GeeksforGeek']
function App() {
const [lists, setLists] = useState(blogLists)
const addBlog = (newVal) => {
setLists(prevState => ['elpeeda', ...prevState])
}
return (
<div className="App">
{lists.map(list => {
return <p key={list.toString()}>{list}</p>
})}
<button onClick={addBlog} type='button'>Button</button>
</div>
);
}
Go Ahead and call this setter function multiple times you'll see it render the value as expected.
Conclusion
In this React tutorial, we covered the most frequent mistakes that react developers make as well as how to handle error messages.
0 Comments:
Post a Comment