Would somebody be so awesome to help me decode the code?

the entire code is below… but I only have questions on some of the parts of it…

This is a sample code from one of the FreeCodeCamp YouTube Channel…

This section here:

Where do the props come from exactly?
and why is it props.exercise.username ? I would think the username comes from one of the fields on the collection list … but I am not clear on the logics of props.exercise.

const Exercise = props => (
  <tr>
    <td>{props.exercise.username}</td>
    <td>{props.exercise.description}</td>
    <td>{props.exercise.duration}</td>
    <td>{props.exercise.date.substring(0,10)}</td>
    <td>
      <Link to={"/edit/"+props.exercise._id}>edit</Link> | <a href="#" onClick={() => { props.deleteExercise(props.exercise._id) }}>delete</a>
    </td>
  </tr>
)

The other section of the code is this below…

He is mapping this.estate.exercises which comes from the axios results , then he is returning Exercise which is the const just above with the props… what exactly is going on the rest of the code and how does it influence the const Exercise?

exerciseList() {
    return this.state.exercises.map(currentexercise => {
      return <Exercise exercise={currentexercise} deleteExercise={this.deleteExercise} key={currentexercise._id}/>;
    })
  }

Complete code here:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import axios from 'axios';

const Exercise = props => (
  <tr>
    <td>{props.exercise.username}</td>
    <td>{props.exercise.description}</td>
    <td>{props.exercise.duration}</td>
    <td>{props.exercise.date.substring(0,10)}</td>
    <td>
      <Link to={"/edit/"+props.exercise._id}>edit</Link> | <a href="#" onClick={() => { props.deleteExercise(props.exercise._id) }}>delete</a>
    </td>
  </tr>
)

export default class ExercisesList extends Component {
  constructor(props) {
    super(props);

    this.deleteExercise = this.deleteExercise.bind(this)

    this.state = {exercises: []};
  }

  componentDidMount() {
    axios.get('http://localhost:5000/exercises/')
      .then(response => {
        this.setState({ exercises: response.data })
      })
      .catch((error) => {
        console.log(error);
      })
  }

  deleteExercise(id) {
    axios.delete('http://localhost:5000/exercises/'+id)
      .then(response => { console.log(response.data)});

    this.setState({
      exercises: this.state.exercises.filter(el => el._id !== id)
    })
  }

  exerciseList() {
    return this.state.exercises.map(currentexercise => {
      return <Exercise exercise={currentexercise} deleteExercise={this.deleteExercise} key={currentexercise._id}/>;
    })
  }

  render() {
    return (
      <div>
        <h3>Logged Exercises</h3>
        <table className="table">
          <thead className="thead-light">
            <tr>
              <th>Username</th>
              <th>Description</th>
              <th>Duration</th>
              <th>Date</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            { this.exerciseList() }
          </tbody>
        </table>
      </div>
    )
  }
}

how much experience do you have with React? props are one of the basic features of React

1 Like

Exercise is a function. It takes one parameter. That’s been called props. The will be an object (it is a React component, this is always be the case). One of the properties is presumably called exercise. That is also, presumably, an object, and it has some properties (username, description, date etc)

1 Like

Wild guess… where do you think I would find the object from which the props are coming from?

This code is for pulling data from a MongoDB list… the list is about an exercise table with inputs such as username, description, duration…

If I am not mistaken, axios is pulling the data and calling it exercises… then exerciseList() is mapping that data… but I don’t see the props in any of this code…

If I am not mistaken again… the guy in the video says the prop information is coming from the exerciseList() function… again… .I don’t see the props…

Would those props be coming directly from the MongoDB collection chart? I know the values of username, description, duration are from that same chart… but where is that exercise prop?

below is how the MongoDB collection looks like… I can see an array with username, description, etc… but yes… where is that exercise in the props coming from?

This is the code from the exercises router that it is being post to the /exercises page that axios is getting information…

could it be that the {props.exercise.username} be coming from the router backend file? if so, from which one of the routes? …

const router = require('express').Router();
let Exercise = require('../models/exercise.model');

router.route('/').get((req, res) => {
  Exercise.find()
    .then(exercises => res.json(exercises))
    .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/add').post((req, res) => {
  const username = req.body.username;
  const description = req.body.description;
  const duration = Number(req.body.duration);
  const date = Date.parse(req.body.date);

  const newExercise = new Exercise({
    username,
    description,
    duration,
    date,
  });

  newExercise.save()
  .then(() => res.json('Exercise added!'))
  .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/:id').get((req, res) => {
  Exercise.findById(req.params.id)
    .then(exercise => res.json(exercise))
    .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/:id').delete((req, res) => {
  Exercise.findByIdAndDelete(req.params.id)
    .then(() => res.json('Exercise deleted.'))
    .catch(err => res.status(400).json('Error: ' + err));
});

router.route('/update/:id').post((req, res) => {
  Exercise.findById(req.params.id)
    .then(exercise => {
      exercise.username = req.body.username;
      exercise.description = req.body.description;
      exercise.duration = Number(req.body.duration);
      exercise.date = Date.parse(req.body.date);

      exercise.save()
        .then(() => res.json('Exercise updated!'))
        .catch(err => res.status(400).json('Error: ' + err));
    })
    .catch(err => res.status(400).json('Error: ' + err));
});

module.exports = router;

It tells me there are props pass on to the the element… but I can’t find where the props are coming from…

  exerciseList() {
    return this.state.exercises.map(currentexercise => {
      return <Exercise exercise={currentexercise} deleteExercise={this.deleteExercise} key={currentexercise._id}/>;
                       ^props.exercise            ^props.deleteExercise                ^not a prop; key has specific meaning
    })
  }
1 Like
function randomFunc(props) {
  console.log(props)
}

const iJustMadeUpProps='made up props'

randomFunction(iJustMadeUpProps)
// logs "made up props"

I write this short code snippet to remind you how function parameters works and how you might find where they come from. Parameters are local for the function. They are available in its body. If you are looking for where its parameters(arguments) come from(from outside the body), you should look where the function is called and what it passed to it. What is passed to it, is the props you look for, however, they can be with different name or shape. Outside the function, they might and most likely, wont be called “props”, or whatever you refer to them in its body. The case with React is just the same, altho slightly altered in the syntax.

const MyReactComponent(myProps){
  console.log(myProps)
  return <div id={myProps.id}>{myProps.text}</div>
}

const AnotherComponent(){
  const id='test'
  const text='some words'

  return <MyReactComponent id={id} text={text} />
}

//console.log(myProps) output: {id: 'test', text: 'some words'}

//expected html result

<div id='test'>some words</div>

This is a very simplified version on how props migrate in the different layers and where they might come from. I strongly advise you, dont look where they come from in the particular case, but try to understand where they come from, when we talk about React, or JS as a whole, so you can read any code. In my example, the props object, which i called “myProps”, originate from the id and text variables i defined in the parent compontent(AnotherComponent) and passed as attributes to the MyReactComponent component.

PS: props object is the way React compontents receive attributes they get. For example, you push several attributes to a component(id, class, onclick function, text, your favorite pet name etc) and under the hood, React place all of those, their respective name and value inside the “props” object. This object is then the first thing you can access, from the component parameters. You can name this object as you like, but its better to keep it clear what it represents, in case another person read your code, of in case you have hard time to figure out later where that thing came from ^^ .

2 Likes

Thank you very much for all your information…

Given the awesome re-freshment on props I got… it makes it easier to understand, however… the visualization of the props.exercise.username, etc still not there… not there because it is obviously not written that way in this code.

However… I now suspect of the right answer to my question of WHERE these props are coming from and HOW were they generated to begin with…

In this code below…

exerciseList() {
    return this.state.exercises.map(currentexercise => {
      return <Exercise exercise={currentexercise} deleteExercise={this.deleteExercise} key={currentexercise._id}/>;
    })
  }

He is mapping “exercises” which is the result of the axios data that got from the http address… then… he got (currentexercise) in another inside function that returns the prop exercise = {currentexercise}… {currentexercise} would have the information of username, description, duration, etc from the MongoDB collection that was gotten from axios under “exercises”… anyway… I think that is how it works…

I want to understand the chain events/logic of the code so that I can also do the same type of operation… .the logic of the operation can change later, but understanding how something is passing information to another point gives me a more clear picture of the entire code.

Thanks much…

1 Like

Yes, you are on the right track. The code takes the state value exercises and maps it. Apparently exercises refers to your data. Im unsure the format of the data, but it looks like each exercise is an object and for every such object you put an Exercise component(element), where you pass as props the exercise, the deleteExercise method and as key the exercise id(the key is important to React, when we create a list of elements and must be unique for each element in the list; the _id is innate attribute for MongoDB documents, being unique for every document, so its comfortable use for the “key”; its generated automatically for every mongo document). He is ultimately returning a list(array) of components/elements, which can be incorporated in the html document directly, thanks to react functionality.
The state is indeed the data returned from the database call(doesnt really look like you connect to a real database).

1 Like

Yes… exercises is the result of the mapping from axios of the MongoDB collection… the collection does include the username, duration, etc…

I also had questions of why using deleteExercise={this.deleteExercise} and key={currentexercise._id} on the exerciseList() function… but now I see they are also being used in the const Exercise = props => ( component…

So… all clear now… I see how the data is being passed and where it comes from…

thanks much…

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.