'Implement show more and show less in react hooks page throws error of undefined
While trying to implement Show More and Show less in my React hooks page, I am getting Cannot read properties of undefined ( reading substring). Could someone please advise what could be the issue ?
The above error occurred in the component:
at MiddleSection (http://localhost:3000/main.2efdffa93468c998df75.hot-update.js:92:82)
at div
at Home
at Routes (http://localhost:3000/static/js/bundle.js:41795:5)
at Router (http://localhost:3000/static/js/bundle.js:41728:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:40537:5)
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
logCapturedError @ react-dom.development.js:18525
update.callback @ react-dom.development.js:18558
callCallback @ react-dom.development.js:13092
Uncaught TypeError: Cannot read properties of undefined (reading 'substring')
at MiddleSection (middleSection.js:56:1)
// textData1.js
import React from 'react';
const TextData ="We are an awesome bunch of friendly people. We play together for fun and enjoy every moments of soccer.";
export default TextData
//middleSection.js
import React, { useState } from 'react';
import data1 from "../data/textData1";
const MiddleSection = () => {
const [showMore, setShowMore] = useState(false);
const { text } = TextData;
return (
<div className='row'>
<div className="middleTextContent">
<p id="middleTextOverlay">
{showMore ? text : `${text.substring(0, 50)} `}
<button className='showMoreLess' onClick={ () =>
setShowMore(!showMore)}>
{showMore ? "Show less": "Show More"}
</button>
</p>
</div>
</div>
)
}
export default MiddleSection;
Solution 1:[1]
There are two reasons why you might have this issue:
- There is no a
TextDatavariable in the scope of themiddleSection.jsfile TextDatais exported as a string fromtextData1.js, hence it can't be destructured
Replace the following line
text.substring(0, 50)
by
data1.substring(0, 50)
And remove the line
const { text } = TextData;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
