Phil Schuster
Phil Schuster

Reputation: 3

React How to pass arguments to function

Hi I found a question asking the same thing but they coded completely different using 'class name extends', I am just using 'function name'. I was wondering how I would I solve this problem or do I have to rewrite my program.

I have styles at the bottom I left off.

Window.js

import React from 'react';
import "../css/Start.css";



export default function Window(nuts) {

    let ulList=[]
    for (let i=0;i<nuts.file.length;i++) {
      ulList.push(<li>
        {
            nuts.file[i]
        }
      </li>)
    }


    let imageList=[]
    for (let i=0;i<nuts.image.length;i++) {
        imageList.push(<img src={nuts.image[i]} alt={nuts.image[i]}/>)
    }


    return (
        <div style={main}>
            <p>{nuts.name}</p>
            <p>{nuts.date}</p>
            <p>{nuts.note}</p>
          {ulList}
          {imageList}
          <button> Demo </button>


        </div>
    );
  }

Project.js

import React from 'react';
import Background from '../images/projectbackground.jpg';
import "../css/Start.css";
import Window from './Window'



export default function Project() {

  const files = ['f1','f2','f3']
  const images = ['p1','p2','p3']
  const nuts = {name:'phil',date:'2/2/16',note:'this is a note',file:files,image:images}

  return (
      <div style={main}>
          <Window nuts={nuts}/>
          <div style={footer}>

          </div>
      </div>
  );
}

Upvotes: 0

Views: 264

Answers (2)

natevw
natevw

Reputation: 17903

Your function component will get passed all the properties together in an object.

There are three changes you could make to have this work:

  • render <Window {...{nuts}} /> instead (not recommended but is an option)
  • change parameters to function Window(props) and all your other code to say props.nuts instead of just nuts
  • change parameters to function Window({nuts}) to destructure the (no longer named) "props" object

Upvotes: 1

Tim
Tim

Reputation: 370

nuts is being passed to Window via the props object.

You either need to destructure nuts in-line or in your function body.

function Window({ nuts }) 

or

function Window(props) {
    const { nuts } = props;
}

Upvotes: 0

Related Questions