I am trying to move individual components with inline styles as I want them in different places of the website. Why is this code not working?
import "./App.css";
import React from "react";
import Window from "./components/Window";
class App extends React.Component {
render() {
return (
<div className="App">
<Window
id="firstWindow"
style={{ position: "relative", left: "200px" }}
number={"1"}
/>
<Window id="secondWindow" number={"2"} />
<Window id="thirdWindow" number={"3"} />
</div>
);
}
}
export default App;
this code works in a different section of the app
import React from "react";
import "./Window.css";
class Window extends React.Component {
render() {
return (
<div
className="square"
style={{ position: "relative", left: "200px" }}
>
{this.props.number}
</div>
);
}
}
export default Window;
CodePudding user response:
So here's a code sandbox with a working example based on your code-
https://codesandbox.io/s/strange-borg-hd2o4?file=/src/App.js
First of all, you need to be using position: absolute
if you're going to use left: 200px
. When it's position: relative
, there's no effect.
Secondly, a better way to style these is to use the ids you've already created and then pass it as a prop to the component, check out the example.
Thirdly, React class components are on the way out - you should be learning the React function approach first. I recommend https://fullstackopen.com/en/.
Hopefully that all makes sense!
CodePudding user response:
Inline style is passed by property name style
, use it to set style in the component.
style={ this.props.style }
A demo:
class App extends React.Component {
render() {
return (
<div className="App">
<Window
id="firstWindow"
style={{ position: "relative", left: "200px" }}
number={"1"}
/>
<Window
id="secondWindow"
style={{ position: "relative", left: "100px" }}
number={"2"} />
<Window
id="thirdWindow"
style={{ position: "relative", left: "10px" }}
number={"3"} />
</div>
);
}
}
class Window extends React.Component {
render() {
return (
<div
className="square"
style={ this.props.style }
>
{this.props.number}
</div>
);
}
}
// ========================================
ReactDOM.render(
<App />,
document.getElementById('root')
);
.square {
background: #fff;
border: 1px solid #999;
float: left;
font-size: 24px;
font-weight: bold;
line-height: 34px;
height: 34px;
margin-right: -1px;
margin-top: -1px;
padding: 0;
text-align: center;
width: 34px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>