kayee
kayee

Reputation: 340

Using props as the key property in React inline style

In React, inline styles are specified with an object whose key is the camelCased version of the style name. How would you use props as the key value?

E.g.:

const {
    position
} = this.props;

let triangleStyle = {
    borderLeft: '5px solid transparent',
    borderRight: '5px solid transparent',
    `border${position}`: '5px solid red'
};

function Component() {
    return <div style={triangleStyle}></div>;
}

Upvotes: 1

Views: 2172

Answers (3)

Aliaga Aliyev
Aliaga Aliyev

Reputation: 425

const {
    position
} = this.props;

let triangleStyle = {
    borderLeft: '5px solid transparent',
    borderRight: '5px solid transparent'
};

triangleStyle[`border${position}`] = '5px solid red'
function Component() {
    return <div style={triangleStyle}></div>;
}

Upvotes: 0

Craig Ayre
Craig Ayre

Reputation: 1173

Since we are computing the key value for the style we can could:

Put all the logic inside the Component, using computed property names

function Component({ position }) {
  const triangleStyle = {
    borderLeft: '5px solid transparent'
    borderRight: '5px solid transparent',
    [`border${position}`]: '5px solid red',
  }

  return <div style={triangleStyle} />
}

Alternatively, extract the triangle styles to a function

const getTriangleStyle = position => ({
  borderLeft: '5px solid transparent'
  borderRight: '5px solid transparent',
  [`border${position}`]: '5px solid red',
})

function Component({ position }) {
  return <div style={getTriangleStyle(position)} />
}

Upvotes: 0

Max Gram
Max Gram

Reputation: 695

Try something like:

const triangleStyleFoo = (position) => ({
    borderLeft: '5px solid transparent',
    borderRight: '5px solid transparent',
    `border${position}`: '5px solid red'
});

function Component() {
    const { position } = this.props;
    const triangleStyle = this.triangleStyleFoo(position);
    return <div style={triangleStyle}></div>;
}

Upvotes: 1

Related Questions