1

Im trying to use a dynamic style property. The approach below throws me an "The style prop expects a mapping from style properties to values, not a string" error.

class someClass extends React.Component {
    someFunction = () => {
        return {marginLeft : 20 };
    }
    render() {
        return( <div style={this.someFunction}/>
        );
    }
}

Howerver this one works:

class someClass extends React.Component {
    render() {
        return( <div style={{marginLeft : 20}}/>
        );
    }
}

Why is that so and how can i return style objects from functions?

Thanks for any answers in advance!

1 Answer 1

8

You didn't call the function inside the style props JSX. Call it like this.someFunction(), then it will return the object of style you kept inside the someFunction.

return <div style={this.someFunction()} />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.