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;
CodePudding user response:
TextData
is a string, so when you destructure it with const { text } = TextData
, text
(which isn't a property on Strings) should be undefined.
If you remove the destructuring and then refer to TextData
directly, it should work.
CodePudding user response:
There are two reasons why you might have this issue:
- There is no a
TextData
variable in the scope of themiddleSection.js
file TextData
is 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;