Search code examples
javascriptcssreactjscreate-react-app

class component with background property invisible


I have got a class component Tile here is its code, its in a separate JSX file:

import React from 'react';

export default class Tile extends React.Component {
    render() {
        return (
            <div
                style={{
                    width:"16px",
                    height:"16px",
                    background: `url('${this.props.tiles}') no-repeat
                ${+this.props.x * -16} ${+this.props.y * -16}`
                }}
                className={`tile${this.props.aClass ? ' ' + this.props.aClass : ''}`}
            ></div>
        );
    }
}

Here is the app.jsx:

import React from 'react';
import Tile from './components/tile.jsx';

function App() {
    return (
        <div className="App">
            <Tile tiles="./assets/Tilemap/tiles_packed.png" x="0" y="0" />
        </div>
    );
}

export default App;

the Tile is being rendered but it is invisible, why?


Solution

  • Couple of things to look for after looking at your code

    • Import the image as it is not present in public folder to serve.
    • Manifest files contain some .png related stuff which needs to be removed for the error in console as per this Q - Read more here
    • Don't pass the path of the file from components which are not in same folder hierarchy - why ? It's basic that the path gets changed and resource fails to load which is obvious ...

    Modify the parts of code as:

    App.tsx:

    import React from 'react';
    import Tile from './components/tile.jsx';
    import tiles_packed from "./assets/Tilemap/tiles_packed.png" // this get's the image and pass it any where you want
    
    function App() {
        
        return (
            <div className="App">
                <Tile tiles= {tiles_packed} x="0" y="0" />
            </div>
        );
    }
    
    export default App;

    tile.jsx

    import React from 'react';
    
    export default class Tile extends React.Component {
        render() {
            return (
                <div
                    style={{
                        "minWidth": '16px', // change styles to view image 
                        "minHeight": '16px',
                        background: `url(${this.props.tiles}) no-repeat
                    ${+this.props.x * -16} ${+this.props.y * -16}`,
                    }}
                    className={`tile${this.props.aClass ? ' ' + this.props.aClass : ''}`}
                ></div>
            );
        }
    }