Skip to content
Advertisement

function is declared but its value is never read : React

I am new to Reactjs so forgive me if this is lame. I am following the Reactjs docs for learning React and during the self implementation of exercise in components and props. And I encountered following weird behaviour: In the ‘Comment’ function <UserInfo ../> tag is working fine but <commentText ../> and <commentDate ../> is not working and for their respective functions VScode is saying that they are declared but their value is never used.

function formatDate(date) {
  return date.toLocaleDateString();
}

function Avatar(props) {
  return (
     <img className="Avatar"
       src={props.user.avatarUrl}
       alt={props.user.name}/>
  );
}

function UserInfo(props){
  return (
    <div className="UserInfo">
      <Avatar user={props.person} />
      <div className="UserInfo-Name">
        {props.person.name}
      </div>
      </div>
  );
}

function commentText(props){
  return (
    <div className="Comment-text">
      {props.sentence}
    </div>
   );
}

function commentDate(props){
  return(
    <div className="Comment-date">
        {formatDate(props.dates)}
     </div>
  );
}

function Comment(props) {
  return (
    <div className="Comment">
      <UserInfo person={props.author}/>
      <commentText sentence={props.text} />
      <commentDate dates={props.date} />
     </div>
  );
}

const comment = {
  date: new Date(),
  text: 'I hope you enjoy learning React!',
  author: {
    name: 'Hello Kitty',
    avatarUrl: 'https://placekitten.com/g/64/64',
  },
};
ReactDOM.render(
  <Comment
    date={comment.date} text={comment.text}author={comment.author}
  />,
  document.getElementById('root')
);
<html>
<head>
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
</head>
<body>
  <div id="root"></div>
</body>
</html>

Advertisement

Answer

Rename:

function commentText(props){

to

function CommentText(props){

and:

function commentDate(props) {

to

function CommentDate(props) {

Then:

<div className="Comment">
  <UserInfo person={props.author}/>
  <CommentText sentence={props.text} />
  <CommentDate dates={props.date} />
</div>

React components are different from regular functions such that their first letter must be capital. It is good practice to structure react components as:

const CommentDate = (props) => {}

instead of

function CommentDate(props) {}

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement