How to resize SVG to fill its container in ReactJS?
We can resize SVG to fill its container in ReactJS using the type props. We can add the following style to the SVG
CSS Syntax:
svg { width: inherit; height: inherit; }
React Syntax:
<svg style = {{ width: "inherit", height:"inherit"}} // Child elements </svg>
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import { React, Component } from "react" ; class App extends Component { render() { return ( <> <div style={{ backgroundColor: "#ddd" , height: 200 }}> <MySvg width= "20%" /> </div> <br /> <div style={{ backgroundColor: "#ddd" , height: 300, width: 200 }}> <MySvg width= "80%" /> </div> </> ); } } const MySvg = (props) => { return ( // With Styling <svg style={{ width: "inherit" , height: "inherit" }} version= "1.1" viewBox= "0 0 31.921 36.45" {...props} > <g transform= "translate(-20.655 -17.456)" > <path d= "m51.254 44.131-14.638 8.451-14.638-8.451v-16.902l14.638-8.451 14.638 8.451z" fill= "none" stroke= "#fb00ff" stroke-linejoin= "round" stroke-width= "2.6458" /> </g> </svg> ); } export default App |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
- Before applying the style props, the following will be the output:
- After applying style props, the following will be the output:
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!