React - Pass an Array as Props

Tell us what’s happening:
So I know that the challenge is asking to use the join method but i wanted to experiment a bit and see what would happen if I wouldn’t use it and it ends up rendering the array as “workoutcode”, shouldn’t it render it as [“workout”, “code”] if I don’t use the join method on props.tasks?

Your code so far

const List = (props) => {
  { /* Change code below this line */ }
  return <p>{props.tasks.}</p>
  { /* Change code above this line */ }
};

class ToDo extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return (
      <div>
        <h1>To Do Lists</h1>
        <h2>Today</h2>
        { /* Change code below this line */ }
        <List tasks = {["workout", "code"]}  />
        <h2>Tomorrow</h2>
        <List tasks = {["play guitar", "run", "walk the dog"]}/>
        { /* Change code above this line */ }
      </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36

Challenge: React - Pass an Array as Props

Link to the challenge:

createElement which is what JSX uses can accept an array for children (which is why you can use map for JSX as well).

You can use the online Babel repl to see the JSX transpiled output.

Example:

import { createElement } from 'react';

function App() {
  return createElement('p', null, ['This ', 'will ', 'create a ', 'sentence.']);
}

export default App;

But I was wondering why doesn’t it render the brackets?

Because that isn’t how the createElement API works.

It also wouldn’t be very useful if it did. Having React render a stringified array doesn’t serve any purpose.

So React in cases like these just renders the array’s contents all joined together with no commas in between and no braces?

I’m sure that is an oversimplification, but yes something like that. It uses the elements in the array, not the array.

createElement puts the array on props.children I’m guessing the actual render (or some part of the render process) is responsible for handling the array. I really do not know React that deeply to properly explain how it handles the array.

https://github.com/facebook/react/blob/540bab085d571789f4562565eebfd0db9f36345c/packages/react/src/ReactElement.js#L362

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