Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: How to pass width as a prop from the component

I am trying to create a component, whose width can be specified wherever the component can be used

Like:

<Button label="button" width="80%" />

const TestButton = styled.button`
  color: red;
`;

var React = require('react');

var Button = React.createClass({

render: function () {

return (
  <TestButton>{this.props.label}</TestButton>
);
}
});

module.exports = Button;

how can I achieve this?

like image 445
userNotHere Avatar asked Dec 08 '17 15:12

userNotHere


Video Answer


2 Answers

You can pass width as props to button component like,

export const Button = (props) => { // Your button component in somewhere
    return (
        <button style={{width: `${props.width}`}}>{props.label}</button>
    )
}

In your main component import your button and work as what you want like below

import Button from 'your_button_component_path';

class RenderButton extends React.Component {
    render() {
        return (
            <Button width="80%" label="Save" />
        );
    }
}
like image 187
Elumalai Kaliyaperumal Avatar answered Oct 08 '22 09:10

Elumalai Kaliyaperumal


If you're using styled-components you can pass the width prop to the component and set its width:

<Button label="button" width="80%" />

const TestButton = styled.button`
  color: red;
  width: ${(props) => props.width}
`;

var React = require('react');

var Button = React.createClass({

  render: function () {

    return (
      <TestButton width={this.props.width}>{this.props.label}</TestButton>
     );
    }
  });

module.exports = Button;
like image 33
AranS Avatar answered Oct 08 '22 08:10

AranS