Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add dynamic html attributes to child component from parent component - React.js

Tags:

reactjs

Child Component:

export default class Button extends React.Component {
constructor(props) {
    super(props);
}
render() {
 return(
        <div className="form-group">
            <button

                // Need to add dynamic html attr here e.x: data-id

                key={index} 
                id={id} 
                className={`btn btn-default ${componentClass ? componentClass : null }`} 
                type="button"
                onClick={this.props.onClick}> 

                {text}

            </button>
        </div>
    );}}

Parent Component :

import Button from './Button';

Class App extends React.Component {
    constructor(props) {
        super(props);
    }
    render() {
        return (
            <div className="s">
             <Button data-id="exampleData" />  // Need to add data-id attr to child button
            </div>
        );
    }

Button Component, have it's own default attributes like mentioned above : id,className,type,onClick

Parent Component, will call Button component and add some additional attributes like data-id,onChange.

note : after searched few ideas, I know that i can use spread operators like below :

Parent Component :

let dynamicAttributes = {"data-id":"someString", "data-attr":"someString", "data-url":"someString"};
    return (
        <div className="s">
         <Button dataSrc={ btnSrc } {...dynamicAttributes} />
        </div>
    );

I don't know how to call the dynamicAttributes in Button component as a html attrib

Expecting a good solution to this. Thanks in advance.

Used Destructing and Babel Showing error(unexpected token) like below image.

enter image description here

note: Already installed preset-env and preset-react.

like image 545
Balaji731 Avatar asked Feb 12 '18 13:02

Balaji731


People also ask

How do you pass variable from parent to child in React?

To pass data from child to parent component in React:Pass a function as a prop to the Child component. Call the function in the Child component and pass the data as arguments. Access the data in the function in the Parent .

How do you pass state from parent to child in React class component?

First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.

How can you update parent component from child component?

To update the parent state from the children component, either we can use additional dependencies like Redux or we can use this simple method of passing the state of the parent to the children and handling it accordingly.


2 Answers

You can make use of rest destructuring pattern in the child component. According to the documentation

Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

You should use rest destructing carefully when you are directly assigning the props to the DOM element, since from v16 onwards no check is done on the attributes and all properties are allowed to be passed on the DOM element, so even if it is not relevant, the properties will be passed on to the DOM element which you might not intend

P.S. Make sure that all properties that you don't want to pass on to the DOM are destructured separately.

Sample snippet

export default class Button extends React.Component {
  constructor(props) {
      super(props);
  }
  render() {
     const { onClick, dataSrc, ...rest } = this.props;
     return(
          <div className="form-group">
              <button
                  {...rest}
                  key={index} 
                  id={id} 
                  className={`btn btn-default ${componentClass ? componentClass : null }`} 
                  type="button"
                  onClick={onClick}> 

                  {text}

              </button>
          </div>
      );
  }
}
like image 124
Shubham Khatri Avatar answered Oct 07 '22 18:10

Shubham Khatri


If you want to pass selective props, you can do:

<button 
  dataSrc={ btnSrc }
  data-id={this.props.data-id}
  data-attr={this.props.data-attr}
  data-url={this.props.data-url}
  key={index} 
  id={id} 
  className={`btn btn-default ${componentClass ? componentClass : null }`} 
  type="button"
  onClick={this.props.onClick}
> 
  {text}
</button>

And if you want to pass all the dynamic attributes, you should destructure the props accordingly. Something like this: {onClick, dataSrc, ...dynamicAttrs} = this.props; and then pass them like this:

<button 
  {...dynamicAttrs}
  dataSrc={ btnSrc }
  key={index} 
  id={id} 
  className={`btn btn-default ${componentClass ? componentClass : null }`} 
  type="button"
  onClick={this.props.onClick}
> 
  {text}
</button>

Also,visit this for reference: Transferring props

like image 3
Arslan Tariq Avatar answered Oct 07 '22 18:10

Arslan Tariq