2

I'm using create react app and I need to assign props values to a styles of the component. In this case background image 'url' is need to pass as props to styles.

index.js

import React from "react";
import ReactDOM from "react-dom";

import Background from "./background";

import "./styles.css";

function App() {
  return (
    <div className="App">
      <Background source="./assets/image.jpg" />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

background.js

import React from "react";

const styles = {
  backgroundImage: "url()"
};

export default class Background extends React.Component {
  render() {
    return <div style={styles.background} />;
  }
}

Find the code on below link: codcodesandbox example

1
  • 1
    in Background component access through this.props.source. Oct 20, 2019 at 5:57

1 Answer 1

6

you can create style object and update the component style prop with it like so:


  render() {
    const style = {
      backgroundImage:`url(${this.props.image})`
    }
    return <div style={style} />;
  }

check this code update

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.