Asking
Asking

Reputation: 4200

How to Pass props in React component?

I am using reactjs. I have a componnt that is written like this:

import MyComponent from './Component';


 const test = [
    {
      id: '1',
      Component: FirstComponent,
    },
    {
      id: '2',
      Component: MyComponent,
    },
  ];

  return (
    <Demo
      components={test} 
    />
  );

In this case How can I pass props for MyComponent?

Upvotes: 1

Views: 65

Answers (2)

Drew Reese
Drew Reese

Reputation: 203542

If you need to pass additional props on to MyComponent then you should define an anonymous component in the config so you can pass new props to the child component. Don't forget to also pass props on through to the child component.

const test = [
  {
    id: '1',
    Component: FirstComponent,
  },
  {
    id: '2',
    Component: (props) => (
      <MyComponent {...props} prop1={prop1} prop2={prop2} etc />
    ),
  },
];

Upvotes: 2

Akshay Rathod Ar
Akshay Rathod Ar

Reputation: 309

Firstly i want to introduce what is props . props means property that you are passing though your jsx code to functions or we can say pure functions . let me give you a demo with small element like H1 Tag .

I am creating a h1.js File .

import React from 'react';

// arrow function that get props
const H1 = (props) => {
     return '<h1>{props.text}</h1>';
}
export default H1;

Now when you want to use this function just import and pass though props like

#Main.js

import React from 'react';
import H1 from './h1.js';
class Main extends React.Component{
   constructor() {
     super();
   }
   render(){
     return(
        <>
          <H1 text="pass what you want"></H1>
        </>
     );
   }
}

so may be you will get idea how it work right ;)

Upvotes: 1

Related Questions