userNotHere
userNotHere

Reputation: 97

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?

Upvotes: 5

Views: 13239

Answers (3)

Elumalai Kaliyaperumal
Elumalai Kaliyaperumal

Reputation: 1520

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" />
        );
    }
}

Upvotes: 7

AranS
AranS

Reputation: 1891

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;

Upvotes: 4

achyut pokhrel
achyut pokhrel

Reputation: 746

You can pass it as props in this way

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

And create Button component.

export const Button = (props) => {
return(
    <button
    style={{width: props.width}}   // or you can pass whole style object here
     >
    {props.label}
    </button>
);
}

You can pass width in both pixel and percentage.

Upvotes: 5

Related Questions