JSX and styling

JSX is the syntax extension for JavaScript. It is not mandatory to use JSX with React but there are some benefits that make development easier. JSX, for example, prevents injection attacks because all values are escaped in the JSX before they are rendered. The most useful feature is that you can embed JavaScript expressions in the JSX by wrapping it with curly brackets and that will be used a lot in the following chapters. In this example, we can access the component props when using JSX. The component props are covered in the next section:

class Hello extends React.Component {
render() {
return <h1>Hello World {this.props.user}</h1>;
}
}

You can also pass a JavaScript expression as props:

<Hello count={2+2} />

JSX is compiled to the React.createElement() calls by Babel. You can use both internal or external styling with the React JSX elements. The following are two examples of inline styling. The first one defines the style straight inside the div element:

<div style={{height: 20, width: 200}}>
Hello
</div>

And the second example creates the style object first, which is then used in the div element. The object name should use the camelCase naming convention:

const divStyle = {
color: 'red',
height: 30
};

const MyComponent = () => (
<div style={divStyle}>Hello</div>
);

As shown in the previous section, you can import a style sheet to the React component. To reference classes from the external CSS file, you should use a className attribute:

import './App.js';

...

<div className="App-header">
This is my app
</div>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.21.158